package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.help.condition.ConditionHelper;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.FieldAttrConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.AddressEnum;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.clazz.ConditionClass;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.ConditionListHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.CluePublicPoolModel2SeniorPojo;
import com.xbongbong.paas.pojo.CustomerPublicPoolModel2SeniorPojo;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.pojo.PublicGroupSyncDetailPojo;
import com.xbongbong.paas.pojo.PublicRuleLabelPojo;
import com.xbongbong.paas.pojo.SyncConditionPojo;
import com.xbongbong.paas.pojo.SyncFilterPojo;
import com.xbongbong.paas.pojo.SyncFilterScreenPojo;
import com.xbongbong.paas.pojo.SyncLabelValuePojo;
import com.xbongbong.paas.pojo.SyncRuleValuePojo;
import com.xbongbong.paas.pojo.SyncTriggerScreenPojo;
import com.xbongbong.paas.pojo.dto.ChangePublicPoolModel2SeniorDTO;
import com.xbongbong.paas.pojo.dto.ChangePublicPoolModel2StandardDTO;
import com.xbongbong.paas.pojo.dto.ChangePublicPoolModelStatusDTO;
import com.xbongbong.paas.pojo.dto.ChangeRuleStatusDTO;
import com.xbongbong.paas.pojo.dto.ConfirmChangePublicPoolModelDTO;
import com.xbongbong.paas.pojo.dto.GroupApplyScoreGetDTO;
import com.xbongbong.paas.pojo.dto.GroupObjectiveGetDTO;
import com.xbongbong.paas.pojo.dto.RemindTimeGetDTO;
import com.xbongbong.paas.pojo.dto.RemindTimeSaveDTO;
import com.xbongbong.paas.pojo.dto.TransferBackRuleSeniorDetailDTO;
import com.xbongbong.paas.pojo.dto.TransferBackRuleSeniorSaveDTO;
import com.xbongbong.paas.pojo.vo.ChangePublicPoolModelSeniorVO;
import com.xbongbong.paas.pojo.vo.ChangePublicPoolModelStatusVO;
import com.xbongbong.paas.pojo.vo.CustomerRuleRemindTimeVO;
import com.xbongbong.paas.pojo.vo.TransferBackRuleSeniorItemVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.TransferBackRuleSeniorService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.appmodule.pojo.dto.AppModuleSaveDTO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.PublicSeasSeniorTabEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.PublicPoolErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ClueErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSeniorListVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.CustomerRuleConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ClueAutoAllocationEntity;
import com.xbongbong.saas.domain.entity.ClueRuleEntity;
import com.xbongbong.saas.domain.entity.CustomerRuleEntity;
import com.xbongbong.saas.domain.entity.PublicGroupEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.TransferBackRuleSeniorEntity;
import com.xbongbong.saas.enums.ClueChildTypeEnum;
import com.xbongbong.saas.enums.ClueRuleEnum;
import com.xbongbong.saas.enums.ClueSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CustomerChildTypeEnum;
import com.xbongbong.saas.enums.CustomerRuleEnum;
import com.xbongbong.saas.enums.CustomerSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SeniorFixedGroupEnum;
import com.xbongbong.saas.enums.SeniorPublicGroupTypeEnum;
import com.xbongbong.saas.enums.SeniorRuleValueEnum;
import com.xbongbong.saas.enums.TagTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.factory.publicrule.IOperateClueRuleValue;
import com.xbongbong.saas.factory.publicrule.IOperateRuleValue;
import com.xbongbong.saas.factory.publicrule.OperateClueRuleValueFactory;
import com.xbongbong.saas.factory.publicrule.OperateRuleValueFactory;
import com.xbongbong.saas.help.PublicSeniorLogHelp;
import com.xbongbong.saas.help.PublicSeniorRuleHelp;
import com.xbongbong.saas.model.ClueAutoAllocationModel;
import com.xbongbong.saas.model.ClueRuleModel;
import com.xbongbong.saas.model.CustomerRuleModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.PublicGroupModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.model.TagLinkModel;
import com.xbongbong.saas.model.TransferBackRuleSeniorModel;
import com.xbongbong.saas.service.AppModuleService;
import com.xbongbong.saas.service.PublicGroupService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yanglei
 * @ProjectName xbb-pro
 * @Description: 公海高级模式ServiceImpl
 * @date 2022/4/13 10:59
 */
@Service("transferBackRuleSeniorService")
public class TransferBackRuleSeniorServiceImpl implements TransferBackRuleSeniorService {

    @Resource
    private TransferBackRuleSeniorModel transferBackRuleSeniorModel;
    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PublicSeniorRuleHelp publicSeniorRuleHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PublicGroupService publicGroupService;
    @Resource
    private CustomerRuleModel customerRuleModel;
    @Resource
    private PublicGroupModel publicGroupModel;
    @Resource
    private ClueRuleModel clueRuleModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LabelModel labelModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ClueAutoAllocationModel clueAutoAllocationModel;
    @Resource
    private PublicSeniorLogHelp publicSeniorLogHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private AppModuleService appModuleService;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private TagLinkModel tagLinkModel;
    @Resource
    private ProFormHelp proFormHelp;

    @Resource
    private ConditionHelper conditionHelper;

    private static final Logger LOG = LoggerFactory.getLogger(TransferBackRuleSeniorServiceImpl.class);

    /**
     * 获取该公司高级模式下开启的提醒时间天数，包括转移和退回
     *
     * @param remindTimeDTO 前端传参
     * @return
     */
    @Override
    public CustomerRuleRemindTimeVO getRemindTime(RemindTimeGetDTO remindTimeDTO) throws XbbException {
        CustomerRuleRemindTimeVO remindTimeVO = new CustomerRuleRemindTimeVO();
        Integer businessType = remindTimeDTO.getBusinessType();
        String corpid = remindTimeDTO.getCorpid();
        remindTimeVO.setBackDay(3);
        remindTimeVO.setTransferDay(3);
        try {
            boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
            boolean clueSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                if (customerSeniorModel) {
                    remindTimeVO.setBackDay(publicSeniorRuleHelp.getRemindTimeByAlias(corpid, CompanyConfigEnum.PUBLIC_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias()));
                    remindTimeVO.setTransferDay(publicSeniorRuleHelp.getRemindTimeByAlias(corpid, CompanyConfigEnum.TRANSFER_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias()));
                } else {
                    remindTimeVO.setBackDay(publicSeniorRuleHelp.getRemindTimeByAlias(corpid, CompanyConfigEnum.PUBLIC_RULE_REMIND_TIME.getAlias()));
                }
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                if (clueSeniorModel) {
                    remindTimeVO.setBackDay(publicSeniorRuleHelp.getRemindTimeByAlias(corpid, CompanyConfigEnum.PUBLIC_RULE_CLUE_SENIOR_REMIND_TIME.getAlias()));
                    remindTimeVO.setTransferDay(publicSeniorRuleHelp.getRemindTimeByAlias(corpid, CompanyConfigEnum.TRANSFER_RULE_CLUE_SENIOR_REMIND_TIME.getAlias()));
                } else {
                    remindTimeVO.setBackDay(publicSeniorRuleHelp.getRemindTimeByAlias(corpid, CompanyConfigEnum.CLUE_PUBLIC_RULE_REMIND_TIME.getAlias()));
                }
            }
            return remindTimeVO;
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 【web】保存公海池退回提醒时间
     *
     * @param remindTimeSaveDTO 保存公海池退回提醒时间入参
     * @return Integer
     * @throws XbbException 业务异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveRemindTime(RemindTimeSaveDTO remindTimeSaveDTO) throws XbbException {
        Integer saveRemindTimeId = null;
        try {
            saveRemindTimeId = saveRemindTimeAndLog(remindTimeSaveDTO);
        } catch (XbbException e) {
            LOG.error("保存公海池提醒时间失败");
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218002);
        }
        return saveRemindTimeId;
    }


    public Integer saveRemindTimeAndLog(RemindTimeSaveDTO remindTimeSaveDTO) throws XbbException {
        String corpid = remindTimeSaveDTO.getCorpid();
        String userId = remindTimeSaveDTO.getUserId();
        String loginUserName = remindTimeSaveDTO.getLoginUserName();
        Integer businessType = remindTimeSaveDTO.getBusinessType();
        String backDayStr = String.valueOf(remindTimeSaveDTO.getBackDay());
        String transferDayStr = String.valueOf(remindTimeSaveDTO.getTransferDay());
        CompanyConfigEntity backConfig = null;
        CompanyConfigEntity transferConfig = null;
        boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
        boolean clueSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            if (customerSeniorModel) {
                backConfig = companyConfigModel.initConfigEntity(corpid, CompanyConfigEnum.PUBLIC_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias());
                transferConfig = companyConfigModel.initConfigEntity(corpid, CompanyConfigEnum.TRANSFER_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias());
                backConfig.setConfigValue(backDayStr);
                transferConfig.setConfigValue(transferDayStr);
                backConfig.setUpdateTime(DateTimeUtil.getInt());
                transferConfig.setUpdateTime(DateTimeUtil.getInt());
            } else {
                backConfig = companyConfigModel.initConfigEntity(corpid, CompanyConfigEnum.PUBLIC_RULE_REMIND_TIME.getAlias());
                backConfig.setConfigValue(backDayStr);
                backConfig.setUpdateTime(DateTimeUtil.getInt());
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            if (clueSeniorModel) {
                backConfig = companyConfigModel.initConfigEntity(corpid, CompanyConfigEnum.PUBLIC_RULE_CLUE_SENIOR_REMIND_TIME.getAlias());
                transferConfig = companyConfigModel.initConfigEntity(corpid, CompanyConfigEnum.TRANSFER_RULE_CLUE_SENIOR_REMIND_TIME.getAlias());
                backConfig.setConfigValue(backDayStr);
                transferConfig.setConfigValue(transferDayStr);
                backConfig.setUpdateTime(DateTimeUtil.getInt());
                transferConfig.setUpdateTime(DateTimeUtil.getInt());
            } else {
                backConfig = companyConfigModel.initConfigEntity(corpid, CompanyConfigEnum.CLUE_PUBLIC_RULE_REMIND_TIME.getAlias());
                backConfig.setConfigValue(backDayStr);
                backConfig.setUpdateTime(DateTimeUtil.getInt());
            }
        }
        Integer id = null;
        try {
            if (Objects.nonNull(backConfig)) {
                id = companyConfigModel.update(backConfig);
                // 日志
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SET_BACK_TIME_CUSTOMER_RULE), backConfig.getConfigName(), backConfig.getConfigValue());
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.OpenSeaRules, OperateTypeEnum.SET, backConfig.getId().toString(), backConfig.getConfigName(), memo, remindTimeSaveDTO.getHttpHeader());
            }
            if (Objects.nonNull(transferConfig)) {
                companyConfigModel.update(transferConfig);
                // 日志
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SET_BACK_TIME_CUSTOMER_RULE), transferConfig.getConfigName(), transferConfig.getConfigValue());
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.OpenSeaRules, OperateTypeEnum.SET, transferConfig.getId().toString(), transferConfig.getConfigName(), memo, remindTimeSaveDTO.getHttpHeader());
            }
        } catch (Exception e) {
            LOG.error("公司配置保存公海池提醒时间失败，corpid=" + corpid, e);
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218006);
        }
        return id;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer save(TransferBackRuleSeniorSaveDTO seniorSaveDTO) throws XbbException {
        String corpid = seniorSaveDTO.getCorpid();
        Integer businessType = seniorSaveDTO.getBusinessType();
        Long formId = seniorSaveDTO.getFormId();
        Integer type = seniorSaveDTO.getType();
        TransferBackRuleSeniorEntity saveEntity = new TransferBackRuleSeniorEntity();
        Integer insertId = null;
        //获取保存之前的实体
        List<TransferBackRuleSeniorEntity> oldEntities = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, formId, businessType, Arrays.asList(type), null);
        TransferBackRuleSeniorEntity oldEntity = new TransferBackRuleSeniorEntity();
        TransferBackRuleSeniorEntity newEntity = new TransferBackRuleSeniorEntity();
        if (CollectionsUtil.isNotEmpty(oldEntities)) {
            oldEntity = oldEntities.get(0);
            BeanUtil.copyProperties(oldEntity, saveEntity);
            saveEntity.setRuleValue(JSON.parseArray(seniorSaveDTO.getRuleValue().toJSONString()));
            saveEntity.setJsonData(JSON.parseArray(seniorSaveDTO.getJsonData().toJSONString()));
        } else {
            TransferBackRuleSeniorEntity entity = new TransferBackRuleSeniorEntity();
            BeanUtil.copyProperties(seniorSaveDTO, entity);
            entity.setRuleValue(JSON.parseArray(seniorSaveDTO.getRuleValue().toJSONString()));
            entity.setJsonData(JSON.parseArray(seniorSaveDTO.getJsonData().toJSONString()));
            saveEntity = entity;
        }
        insertId = save(seniorSaveDTO, saveEntity);
        //获取保存前后的实体，为后面日志使用
        List<TransferBackRuleSeniorEntity> newEntities = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, formId, businessType, Arrays.asList(type), null);
        newEntity = CollectionsUtil.isNotEmpty(newEntities) ? newEntities.get(0) : new TransferBackRuleSeniorEntity();
        try {
            //日志
            publicSeniorLogHelp.savePublicRuleLog(oldEntity, newEntity, seniorSaveDTO, type);
        } catch (Exception e) {
            LOG.warn("日志保存失败");
        }
        return insertId;
    }

    public Integer save(TransferBackRuleSeniorSaveDTO seniorSaveDTO, TransferBackRuleSeniorEntity saveEntity) throws XbbException {
        String corpid = seniorSaveDTO.getCorpid();
        Integer type = seniorSaveDTO.getType();
        Integer businessType = seniorSaveDTO.getBusinessType();

        JSONArray ruleValueArray = FastJsonHelper.parseArray(seniorSaveDTO.getRuleValue().toJSONString());

        if (CollectionsUtil.isNotEmpty(ruleValueArray)) {
            //高级公海模式-其他设置的规则需要校验参数
            if (Objects.equals(type, CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode())) {
                JSONObject ruleValue = (JSONObject) ruleValueArray.get(BasicConstant.ZERO);
                //参数校验
                verifySave4OtherSet(ruleValueArray, type, businessType);
                JSONArray restrictArray = FastJsonHelper.getJsonArrayOrDefault(ruleValue, "restrict", new JSONArray());
                //格式化前端传过来的特殊员工  users
                publicSeniorRuleHelp.formatSaveUsers(restrictArray);
            } else if (Objects.equals(type, CustomerSeniorRuleTypeEnum.PRE_PRINCIPAL_RULE.getCode()) || Objects.equals(type, CustomerSeniorRuleTypeEnum.GAIN_RATE_RULE.getCode())) {
                //参数校验
                verifySave4OtherSet(ruleValueArray, type, businessType);
                //格式化前端传过来的特殊员工  users
                publicSeniorRuleHelp.formatSaveUsers(ruleValueArray);
            } else {
                //高级公海模式-自动退回和自动转移 users格式化
                for (Object obj : ruleValueArray) {
                    JSONObject ruleValue = (JSONObject) obj;
                    JSONObject triggerScreen = FastJsonHelper.getJsonObjectOrDefault(ruleValue, SeniorRuleValueEnum.TRIGGER_SCREEN.getAlias(), new JSONObject());
                    JSONObject filterScreen = FastJsonHelper.getJsonObjectOrDefault(ruleValue, SeniorRuleValueEnum.FILTER_SCREEN.getAlias(), new JSONObject());
                    //String ruleName = FastJsonHelper.getStringOrDefault(ruleValue, "name", "");
                    Integer filterType = filterScreen.getInteger("filterType");
                    //如果筛选条件是按照客户统一设置，清空筛选条件
                    if (Objects.equals(filterType, BasicConstant.ONE)) {
                        filterScreen.put("filterRule", new JSONArray());
                        ruleValue.put(SeniorRuleValueEnum.FILTER_SCREEN.getAlias(), filterScreen);
                    }
                    if (Objects.isNull(triggerScreen)) {
                        continue;
                    }
                    JSONArray triggerScreenArray = FastJsonHelper.getJsonArrayOrDefault(triggerScreen, "rule", new JSONArray());
                    //参数校验
                    //verifySave4Back(triggerScreenArray,ruleName);
                    //格式化前端传过来的特殊员工  users
                    publicSeniorRuleHelp.formatSaveUsers(triggerScreenArray);
                }
            }
        }
        saveEntity.setRuleValue(ruleValueArray);
        saveEntity.setStatus(seniorSaveDTO.getStatus());
        saveEntity.setCreatorId(seniorSaveDTO.getUserId());
        Integer saveId;
        try {
            saveId = transferBackRuleSeniorModel.insert(saveEntity);
        } catch (Exception e) {
            LOG.error("公海池规则数据插入或更新失败，corpid=" + corpid, e);
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218004);
        }
        return saveId;
    }

    /**
     * 客户和线索 - 其他设置规则参数校验，3、最大客户（线索）数，4、前负责人，5、捞取频率
     *
     * @param ruleValueArray 规则值
     * @param ruleType       规则类型
     * @param businessType   业务类型
     * @throws XbbException
     */
    private void verifySave4OtherSet(JSONArray ruleValueArray, Integer ruleType, Integer businessType) throws XbbException {
        String rule = "";
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            CustomerSeniorRuleTypeEnum customerSeniorEnum = CustomerSeniorRuleTypeEnum.getByCode(ruleType);
            switch (customerSeniorEnum) {
                case MAX_CUSTOMER_NUM_RULE:
                    rule = JSON.toJSONString(ruleValueArray.get(BasicConstant.ZERO));
                    break;
                case PRE_PRINCIPAL_RULE:
                case GAIN_RATE_RULE:
                    rule = JSON.toJSONString(ruleValueArray);
                    break;
                default:
                    break;
            }
            IOperateRuleValue operateRuleValue = OperateRuleValueFactory.operateSeniorRuleValueFactory(ruleType);
            operateRuleValue.verify(rule);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            ClueSeniorRuleTypeEnum clueSeniorEnum = ClueSeniorRuleTypeEnum.getByCode(ruleType);
            switch (clueSeniorEnum) {
                case MAX_CLUE_NUM_RULE:
                    rule = JSON.toJSONString(ruleValueArray.get(BasicConstant.ZERO));
                    break;
                case PRE_PRINCIPAL_RULE:
                case GAIN_RATE_RULE:
                    rule = JSON.toJSONString(ruleValueArray);
                    break;
                default:
                    break;
            }
            IOperateClueRuleValue operateClueRuleValue = OperateClueRuleValueFactory.operateSeniorRuleValueFactory(ruleType);
            operateClueRuleValue.verify(rule);
        }
    }


    /**
     * 客户和线索 - 自动退回或者自动转移顾泽参数校验
     *
     * @param triggerScreenArray 规则值
     * @param ruleName           规则名称
     * @throws XbbException
     */
    private void verifySave4Back(JSONArray triggerScreenArray, String ruleName) throws XbbException {
        for (Object ruleObj : triggerScreenArray) {
            Integer value = FastJsonHelper.getIntegerOrDefault((JSONObject) ruleObj, "value", 0);
            //校验设置的天数
            if (value < 1) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, I18nMessageUtil.getMessage(ErrorMessageConstant.NAME_DAYS_GREATER_ZERO), ruleName);
            }
            if (value > 99999) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, I18nMessageUtil.getMessage(ErrorMessageConstant.NAME_MAXIMUM_DAYS), ruleName);
            }
        }
    }

    @Override
    public TransferBackRuleSeniorItemVO getTransferBackRuleItem(TransferBackRuleSeniorDetailDTO seniorDetailDTO) throws XbbException {
        TransferBackRuleSeniorItemVO seniorItemVO;
        try {
            seniorItemVO = packageRuleSeniorItemVO(seniorDetailDTO);
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return seniorItemVO;
    }

    private TransferBackRuleSeniorItemVO packageRuleSeniorItemVO(TransferBackRuleSeniorDetailDTO seniorDetailDTO) throws XbbException {
        TransferBackRuleSeniorItemVO seniorItemVO = new TransferBackRuleSeniorItemVO();
        String corpid = seniorDetailDTO.getCorpid();
        Integer businessType = seniorDetailDTO.getBusinessType();
        Long formId = seniorDetailDTO.getFormId();
        Integer type = seniorDetailDTO.getType();
        // 数据字典项：获取客户状态
        Map<String, String> customerStatusMap = dataDictionaryModel.getDictionaryMap(DictionaryEnum.CUSTOMER_STATUS, corpid, null);
        //获取表单字段
        Map<String, FieldAttrEntity> explainMap = new HashMap<>();
        if (Objects.nonNull(formId)) {
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (explainEntity == null) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218011);
            }
            List<FieldAttrEntity> explainList = JsonHelperUtil.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
            explainList.forEach(fieldAttrEntity -> {
                try {
                    fieldAttrEntity.setItems(proFormHelp.setItemAndComboItems(fieldAttrEntity, paasFormEntityExt));
                } catch (XbbException e) {
                    LOG.error("下拉框字段items获取错误",e);
                }
            });
            explainMap = explainList.stream().collect(Collectors.toMap(FieldAttrEntity::getAttr, FieldAttrEntity -> FieldAttrEntity));
        }

        List<TransferBackRuleSeniorEntity> entities = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, formId, businessType, Arrays.asList(type), null);
        CustomerSeniorRuleTypeEnum ruleTypeEnum = CustomerSeniorRuleTypeEnum.getByCode(type);
        //高级模式-返回自动退回固定数据
        JSONArray filterArray = new JSONArray();
        JSONArray triggerArray = new JSONArray();
        JSONArray chooseArray = new JSONArray();
        publicSeniorRuleHelp.addFixedTypeByBusinessType(businessType, filterArray, triggerArray, chooseArray);
        switch (ruleTypeEnum) {
            case BACK_RULE:
                seniorItemVO.setFilterArray(filterArray);
                seniorItemVO.setTriggerArray(triggerArray);
                seniorItemVO.setChooseArray(chooseArray);
                break;
            case TRANSFER_RULE:
                seniorItemVO.setFilterArray(filterArray);
                break;
            case MAX_CUSTOMER_NUM_RULE:
            case PRE_PRINCIPAL_RULE:
            case GAIN_RATE_RULE:
                //高级模式-返回其他设置页面固定数据
                seniorItemVO.setImportantDegreeArray(publicSeniorRuleHelp.getImportantDegree(false));
                seniorItemVO.setImportantDegreeArraySort(publicSeniorRuleHelp.getImportantDegree(true));
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    seniorItemVO.setTypeArray(customerStatusMap);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                    seniorItemVO.setTypeArray(ClueStatusEnum.getCodeAndNameMap());
                }
                seniorItemVO.setChildTypeArray(publicSeniorRuleHelp.getChildTypeList(true, businessType));
                break;
            default:
                break;
        }
        boolean isOtherSet = Objects.equals(type, CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode())
                || Objects.equals(type, CustomerSeniorRuleTypeEnum.PRE_PRINCIPAL_RULE.getCode())
                || Objects.equals(type, CustomerSeniorRuleTypeEnum.GAIN_RATE_RULE.getCode());
        if (CollectionsUtil.isNotEmpty(entities)) {
            TransferBackRuleSeniorEntity entity = entities.get(BasicConstant.ZERO) != null ? entities.get(BasicConstant.ZERO) : new TransferBackRuleSeniorEntity();
            //不退回规则
            JSONArray jsonArray = entity.getJsonData();
            //退回规则
            JSONArray ruleValueArray = entity.getRuleValue();

            List<PublicGroupSeniorEntity> groupList = publicGroupSeniorModel.getByFormId(formId, corpid, null);

            Map<Long, PublicGroupSeniorEntity> idToEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(groupList)) {
                idToEntityMap = groupList.stream().collect(Collectors.toMap(PublicGroupSeniorEntity::getId, publicGroupSeniorEntity -> publicGroupSeniorEntity));
            }
            //解析前端需要的格式- 退回条件
            analysisRuleValue(ruleValueArray, idToEntityMap, corpid, explainMap, formId, type,businessType);
            //解析前端需要的格式 - 不退回条件
            formatJsonDataValue(jsonArray, corpid, explainMap, formId);

            seniorItemVO.setJsonData(jsonArray);
            seniorItemVO.setRuleValue(ruleValueArray);
            seniorItemVO.setId(entity.getId());
            seniorItemVO.setStatus(entity.getStatus());
        } else if (CollectionsUtil.isEmpty(entities) && isOtherSet) {
            //新公司初始化 ruleValue为null
            Object ruleValue = publicSeniorRuleHelp.initPublicRule(XbbRefTypeEnum.CLUE.getCode(), type, true);
            seniorItemVO.setRuleValue(ruleValue);
            seniorItemVO.setStatus(BasicConstant.ZERO);
        } else {
            seniorItemVO.setStatus(BasicConstant.ZERO);
        }
        return seniorItemVO;
    }

    /**
     * 解析前端需要的格式
     *
     * @param ruleValueArray
     * @param idToEntityMap
     * @param corpid
     * @param explainMap     表单解释
     * @param formId         表单id
     * @param type           规则类型
     */
    public void analysisRuleValue(JSONArray ruleValueArray, Map<Long, PublicGroupSeniorEntity> idToEntityMap, String corpid, Map<String, FieldAttrEntity> explainMap, Long formId, Integer type,Integer businessType) {
        if (CollectionsUtil.isNotEmpty(ruleValueArray)) {
            if (type > CustomerSeniorRuleTypeEnum.BACK_RULE.getCode()) {
                //格式化其他设置中最大线索（客户）数的标签、捞取频率、前负责人规则的特殊员工规则
                formatOtherSetRule(ruleValueArray, corpid, type,businessType);
            } else {
                //格式化自动退回、自动转移的users
                formatBackTransferValue(ruleValueArray, corpid, idToEntityMap, explainMap, formId);
            }
        }
    }

    /**
     * 自动退回和自动转移规则 - 筛选条件jsonData : 格式化标签 items
     *
     * @param jsonDataArray 筛选条件
     * @param corpid        公司id
     * @param explainMap    表单解释
     * @param formId        表单id
     */
    public void formatJsonDataValue(JSONArray jsonDataArray, String corpid, Map<String, FieldAttrEntity> explainMap, Long formId) {
        if (CollectionsUtil.isNotEmpty(jsonDataArray)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("formId", formId);
            param.put("columns", "id,lable_name,form_id,lable_color");
            List<LabelEntity> labelEntityList = labelModel.findEntitys(param);
            Map<Long, String> idToNameMap = labelEntityList.stream().collect(Collectors.toMap(LabelEntity::getId, LabelEntity::getName));
            for (Object o : jsonDataArray) {
                JSONObject jsonObject = (JSONObject) o;
                Integer fieldType = jsonObject.getInteger("fieldType");
                String attr = jsonObject.getString("attr");
                String name = jsonObject.getString("name");
                if (Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())) {
                    JSONArray items = new JSONArray();
                    JSONArray valueItems = new JSONArray();
                    List<Long> finLabelIds = new ArrayList<>();
                    JSONArray labelIds = jsonObject.getJSONArray("value");
                    if (CollectionsUtil.isEmpty(labelIds)) {
                        continue;
                    }
                    for (Object id : labelIds) {
                        Long longId = Long.parseLong(id.toString());
                        if (idToNameMap.containsKey(longId)) {
                            JSONObject item = new JSONObject();
                            item.put("text", idToNameMap.getOrDefault(longId, ""));
                            item.put("value", longId);
                            finLabelIds.add(longId);
                            items.add(item);
                        }
                    }
                    //处理标签删除的情况
                    for (Map.Entry<Long, String> entry : idToNameMap.entrySet()) {
                        JSONObject valueItem = new JSONObject();
                        valueItem.put("text", entry.getValue());
                        valueItem.put("value", entry.getKey());
                        valueItems.add(valueItem);
                    }
                    jsonObject.put("items", items);
                    jsonObject.put("value", finLabelIds);
                    jsonObject.put("valueItems", valueItems);
                }
                FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
                if (Objects.nonNull(fieldAttrEntity)) {
                    String attrName = fieldAttrEntity.getAttrName();
                    jsonObject.put(FieldAttrConstant.IS_OPEN, fieldAttrEntity.getIsOpen());
                    //模板字段删除之后，又添加了相同FieldType的字段，此时之前删除的字段与新添加的字段attr相同，名称也要覆盖
                    if (!Objects.equals(name,attrName)){
                        jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, attrName);
                        jsonObject.put(StringConstant.LABEL, attrName);
                    }
                    //下拉框字段处理
                    if (Objects.equals(FieldTypeEnum.COMBO.getType(),fieldType)){
                        jsonObject.put("items", CloneUtil.deepClone(fieldAttrEntity.getItems()));
                        jsonObject.put("valueItems", JSON.parseArray(JSON.toJSONString(fieldAttrEntity.getItems())));
                    }
                }else {
                    //判断地址类型的字段有没有开启
                    boolean isAddressOpen = false;
                    for (FieldAttrEntity fieldAttr : explainMap.values()){
                        if (Objects.equals(fieldAttr.getAttr(),CustomerManagementEnum.ADDRESS.getAttr()) && Objects.equals(fieldAttr.getIsOpen(),BasicConstant.ONE)){
                            isAddressOpen = true;
                            break;
                        }
                    }
                    if (isAddressOpen && AddressEnum.getByAlias(attr) != null){
                        jsonObject.put(FieldAttrConstant.IS_OPEN, BasicConstant.ONE);
                    }else {
                        jsonObject.put(FieldAttrConstant.IS_OPEN, BasicConstant.ZERO);
                    }
                }
            }
            //处理员工部门的筛选条件
            conditionHelper.handleUserConditions(corpid, jsonDataArray);
        }
    }

    /**
     * 自动退回和自动转移规则 - 退回选择条件ruleValue ： 格式化前端所需结构：适用范围、目标公海、特殊员工
     *
     * @param ruleValueArray 规则数据
     * @param corpid         公司id
     * @param idToEntityMap  分组映射
     * @param explainMap     表单解释
     * @param formId         表单id
     */
    public void formatBackTransferValue(JSONArray ruleValueArray, String corpid, Map<Long, PublicGroupSeniorEntity> idToEntityMap, Map<String, FieldAttrEntity> explainMap, Long formId) {
        for (Object obj : ruleValueArray) {
            JSONObject ruleValue = (JSONObject) obj;
            JSONArray newApplyScopeArray = new JSONArray();
            JSONArray applyScopeArray = FastJsonHelper.getJsonArrayOrDefault(ruleValue, SeniorRuleValueEnum.APPLY_SCOPE.getAlias(), new JSONArray());
            Long groupId = FastJsonHelper.getJsonObjectOrDefault(ruleValue, SeniorRuleValueEnum.OBJECTIVE_GROUP.getAlias(), new JSONObject()).getLong("value");

            JSONObject objectGroup = publicSeniorRuleHelp.getLabelValueMap(groupId, idToEntityMap);
            //适用范围
            for (Object applyScopeObj : applyScopeArray) {
                JSONObject applyScope = (JSONObject) applyScopeObj;
                Long id = applyScope.getLong("value");
                JSONObject labelValueMap = publicSeniorRuleHelp.getLabelValueMap(id, idToEntityMap);
                newApplyScopeArray.add(labelValueMap);
            }
            ruleValue.put(SeniorRuleValueEnum.OBJECTIVE_GROUP.getAlias(), objectGroup);
            ruleValue.put(SeniorRuleValueEnum.APPLY_SCOPE.getAlias(), newApplyScopeArray);
            //触发条件
            JSONObject triggerScreenJson = FastJsonHelper.getJsonObjectOrDefault(ruleValue, SeniorRuleValueEnum.TRIGGER_SCREEN.getAlias(), new JSONObject());
            Integer triggerType = FastJsonHelper.getIntegerOrDefault(triggerScreenJson, "triggerType", 0);
            //封装前端需要的特殊员工格式，全部放到users里面
            if (Objects.equals(triggerType, BasicConstant.ONE)) {
                JSONArray triggerRuleArray = FastJsonHelper.getJsonArrayOrDefault(triggerScreenJson, "rule", new JSONArray());
                publicSeniorRuleHelp.formatReturnUsers(triggerRuleArray, corpid);
            }
            //筛选条件
            JSONObject filterScreen = FastJsonHelper.getJsonObjectOrDefault(ruleValue, SeniorRuleValueEnum.FILTER_SCREEN.getAlias(), new JSONObject());
            JSONArray filterRuleArray = FastJsonHelper.getJsonArrayOrDefault(filterScreen, "filterRule", new JSONArray());

            formatJsonDataValue(filterRuleArray, corpid, explainMap, formId);
        }
    }

    /**
     * 其他设置： 格式化标签返回值的结构和特殊员工users
     *
     * @param ruleValueArray
     * @param corpid 公司id
     * @param type 规则类型
     */
    private void formatOtherSetRule(JSONArray ruleValueArray, String corpid,Integer type,Integer businessType) {
        //特殊员工格式化
        if(Objects.equals(type,CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode())){
            for (Object obj : ruleValueArray) {
                JSONObject ruleValue = (JSONObject) obj;
                Integer backType = ruleValue.getInteger("type");
                //不退回规则的标签格式化
                JSONArray labelIds = FastJsonHelper.getJsonArrayOrDefault(ruleValue, "label", new JSONArray());
                List<PublicRuleLabelPojo> noBckLabelPojos = publicSeniorRuleHelp.getRuleLabelPojos(corpid, JSON.parseArray(labelIds.toJSONString(), Long.class));
                ruleValue.put("label", noBckLabelPojos);
                JSONArray restrictArray = FastJsonHelper.getJsonArrayOrDefault(ruleValue, "restrict", new JSONArray());
                //退回规则的标签格式化,只有最大客户线索数才有
                boolean isLabel = (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(backType, CustomerChildTypeEnum.CUSTOMER_CHILD_THREE_STAR.getCode())) ||
                        (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(backType, ClueChildTypeEnum.CLUE_CHILD_TWO_STAR.getCode()));
                if (isLabel) {
                    for (Object restrict : restrictArray) {
                        JSONObject ruleJson = (JSONObject) restrict;
                        JSONArray valueArr = FastJsonHelper.getJsonArrayOrDefault(ruleJson, "array", new JSONArray());
                        if (valueArr != null) {
                            for (Object o : valueArr) {
                                JSONObject backValue = (JSONObject) o;
                                String key = backValue.getString("key");
                                List<Long> labelIdList = JSONArray.parseArray(key, Long.class);
                                List<PublicRuleLabelPojo> backLabelPojos = publicSeniorRuleHelp.getRuleLabelPojos(corpid, labelIdList);
                                backValue.put("key", JSONObject.toJSONString(backLabelPojos));
                            }
                        }
                    }
                }
                publicSeniorRuleHelp.formatReturnUsers(restrictArray, corpid);
            }
        } else {
            publicSeniorRuleHelp.formatReturnUsers(ruleValueArray, corpid);
        }
    }


    @Override
    public PublicGroupSeniorListVO groupObjectiveGet(GroupObjectiveGetDTO objectiveGetDTO) throws XbbException {
        PublicGroupSeniorListVO ruleSeniorItemVO = new PublicGroupSeniorListVO();
        Long formId = objectiveGetDTO.getFormId();
        String corpid = objectiveGetDTO.getCorpid();
        try {
            JSONArray groupTree = publicGroupSeniorModel.getGroupTree(corpid, formId, BasicConstant.ONE);
            JSONArray allGroupTree = publicSeniorRuleHelp.addFixedGroup(groupTree, false, objectiveGetDTO.getBusinessType(),objectiveGetDTO.getType());
            ruleSeniorItemVO.setGroupTree(allGroupTree);
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return ruleSeniorItemVO;
    }


    @Override
    public PublicGroupSeniorListVO applyScoreGet(GroupApplyScoreGetDTO applyScoreGetDTO) throws XbbException {
        PublicGroupSeniorListVO ruleSeniorItemVO = new PublicGroupSeniorListVO();
        Long formId = applyScoreGetDTO.getFormId();
        String corpid = applyScoreGetDTO.getCorpid();
        Integer type = applyScoreGetDTO.getType();
        try {
            JSONArray openGroupTree = publicGroupSeniorModel.getGroupTree(corpid, formId, BasicConstant.ONE);
            if (Objects.equals(applyScoreGetDTO.getOperateFlag(), BasicConstant.TWO)) {
                //代表是重移动端分组筛选进来的，要过滤无公海分组
                Iterator<Object> iterator = openGroupTree.iterator();
                while (iterator.hasNext()) {
                    JSONObject next = (JSONObject) iterator.next();
                    if (Objects.equals(next.getInteger("groupType"), SeniorPublicGroupTypeEnum.NO_PUBLIC_GROUP.getType())) {
                        iterator.remove();
                        break;
                    }
                }
                openGroupTree = publicSeniorRuleHelp.addFixedGroup(openGroupTree, true, applyScoreGetDTO.getBusinessType(),type);
                ruleSeniorItemVO.setGroupTree(openGroupTree);
            } else if (Objects.equals(applyScoreGetDTO.getOperateFlag(), BasicConstant.ZERO)) {
                //代表是其他入口此时需要添加固定分组
                openGroupTree = publicSeniorRuleHelp.addFixedGroup(openGroupTree, true, applyScoreGetDTO.getBusinessType(),type);
                ruleSeniorItemVO.setGroupTree(openGroupTree);
            } else {
                //代表是变更公海分组进来的,此时不需要添加固定分组
                ruleSeniorItemVO.setGroupTree(openGroupTree);
            }
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return ruleSeniorItemVO;
    }

    @Override
    public Integer changeRuleStatus(ChangeRuleStatusDTO ruleStatusDTO) throws XbbException {
        Integer update = 0;
        try {
            Integer status = ruleStatusDTO.getStatus();
            String corpid = ruleStatusDTO.getCorpid();
            Integer type = ruleStatusDTO.getType();
            Long id = ruleStatusDTO.getId();
            Integer businessType = ruleStatusDTO.getBusinessType();
            Long formId = ruleStatusDTO.getFormId();
            PublicSeasSeniorTabEnum tabEnum = PublicSeasSeniorTabEnum.getByCode(ruleStatusDTO.getTabType());
            //开启了客户公海高级或者线索公海高级
            boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
            boolean clueSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
            boolean isCustomer = Objects.equals(ruleStatusDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            boolean isClue = Objects.equals(ruleStatusDTO.getBusinessType(), XbbRefTypeEnum.CLUE.getCode());
            //是否客户或者线索高级模式
            boolean isCusOrClueSenior = (isCustomer && customerSeniorModel) || (isClue && clueSeniorModel);
            switch (tabEnum) {
                case PUBLIC_GROUP_RULE_SET:
                    PublicGroupEntity publicGroupEntity = new PublicGroupEntity();
                    if (isCusOrClueSenior) {
                        //表示高级模式下，公海分组的状态的更新
                        update = publicGroupSeniorModel.updateBatchStatus(ruleStatusDTO);
                    } else {
                        //表示标准模式下，公海分组的状态的更新
                        publicGroupEntity.setCorpid(corpid);
                        publicGroupEntity.setId(id);
                        publicGroupEntity.setEnable(status);
                        publicGroupEntity.setFormId(ruleStatusDTO.getFormId());
                        update = publicGroupModel.update(publicGroupEntity);
                    }
                    break;
                case PUBLIC_BACK_RULE_SET:
                case PUBLIC_TRANSFER_RULE_SET:
                case PUBLIC_OTHER_RULE_SET:
                    if (isCusOrClueSenior) {
                        //表示高级模式的退回和转移更新  需要传 id
                        if (Objects.isNull(id)) {
                            List<TransferBackRuleSeniorEntity> entities = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, formId, businessType, Arrays.asList(type), null);
                            TransferBackRuleSeniorEntity originEntity = CollectionsUtil.isNotEmpty(entities) ? entities.get(0) : null;
                            if (Objects.isNull(originEntity)) {
                                publicSeniorRuleHelp.initSeniorBackEntity(corpid, businessType, type, formId,ruleStatusDTO.getUserId());
                            }
                            List<TransferBackRuleSeniorEntity> newEntities = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, formId, businessType, Arrays.asList(type), null);
                            TransferBackRuleSeniorEntity newEntity = CollectionsUtil.isNotEmpty(newEntities) ? newEntities.get(0) : new TransferBackRuleSeniorEntity();
                            id = newEntity.getId();
                        }
                        TransferBackRuleSeniorEntity seniorEntity = new TransferBackRuleSeniorEntity();
                        seniorEntity.setId(id);
                        seniorEntity.setCorpid(corpid);
                        seniorEntity.setStatus(status);
                        update = transferBackRuleSeniorModel.update(seniorEntity);
                        break;
                    } else if (isCustomer && !customerSeniorModel) {
                        // 表示标准模式客户退回的 更新状态， 需要传type，不要id
                        CustomerRuleEntity customerRule = new CustomerRuleEntity();
                        CustomerRuleEntity originCustomerRule = customerRuleModel.getByRuleType(type, corpid);
                        if (Objects.isNull(originCustomerRule)) {
                            publicSeniorRuleHelp.initCustomerRuleEntity(corpid, type, businessType);
                        }else {
                            customerRule.setId(originCustomerRule.getId());
                            customerRule.setCorpid(corpid);
                            customerRule.setStatus(status);
                            update = customerRuleModel.update(customerRule);
                        }
                        break;
                    } else if (isClue && !clueSeniorModel) {
                        // 表示标准模式线索退回的 更新状态， 需要传type，不要id
                        ClueRuleEntity clueRule = new ClueRuleEntity();
                        ClueRuleEntity originClueRule = clueRuleModel.getByRuleType(type, corpid);
                        if (Objects.isNull(originClueRule)) {
                            publicSeniorRuleHelp.initClueRuleEntity(corpid, type, businessType);
                        }else {
                            clueRule.setId(originClueRule.getId());
                            clueRule.setCorpid(corpid);
                            clueRule.setStatus(status);
                            update = clueRuleModel.update(clueRule);
                        }
                        break;
                    }
                default:
                    break;
            }
            //日志保存
            try{
                publicSeniorLogHelp.openAndCloseLog(ruleStatusDTO);
            }catch (Exception e){
                LOG.error("公海池启停日志保存失败",e);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return update;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChangePublicPoolModelSeniorVO changePublicPoolModel2Senior(ChangePublicPoolModel2SeniorDTO changePublicPoolModel2SeniorDTO) throws XbbException {
        ChangePublicPoolModelSeniorVO baseVO = new ChangePublicPoolModelSeniorVO();
        Integer businessType = changePublicPoolModel2SeniorDTO.getBusinessType();
        try {
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                baseVO = syncCustomerPublicPool2Senior(changePublicPoolModel2SeniorDTO);
            } else {
                baseVO = syncCluePublicPool2Senior(changePublicPoolModel2SeniorDTO);
            }
            return baseVO;
        } catch (Exception e) {
            LOG.error("同步逻辑出错", e);
            throw e;
        }
    }

    /**
     * 同步客户公海池到高级
     *
     * @author lijiangren
     * @date 2022-05-11 10 44
     */
    private ChangePublicPoolModelSeniorVO syncCustomerPublicPool2Senior(ChangePublicPoolModel2SeniorDTO changePublicPoolModel2SeniorDTO) throws XbbException {
        ChangePublicPoolModelSeniorVO baseVO = new ChangePublicPoolModelSeniorVO();
        Integer businessType = changePublicPoolModel2SeniorDTO.getBusinessType();
        String corpid = changePublicPoolModel2SeniorDTO.getCorpid();
        String userId = changePublicPoolModel2SeniorDTO.getUserId();
        CustomerPublicPoolModel2SeniorPojo customerPublicPoolModel = changePublicPoolModel2SeniorDTO.getCustomerPublicPoolModel2SeniorPojo();
        try {
            //是否是旗舰版
            Integer feeType = packageHelp.getFeeType(corpid);
            if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                throw new XbbException(ClueErrorCodeEnum.API_ERROR_1111013, ClueErrorCodeEnum.API_ERROR_1111013.getMsg());
            }
            boolean publicPoolSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
            if (publicPoolSeniorModel) {
                //已经是高级模式，无法切换到高级
                throw new XbbException(ClueErrorCodeEnum.API_ERROR_1111010, ClueErrorCodeEnum.API_ERROR_1111010.getMsg());
            }
            //查公司配置表判断是否数据切换公海模式中
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.CUSTOMER_PUBLIC_POOL_CHANGE.getAlias(), corpid);
            if (Objects.nonNull(companyConfigEntity)) {
                //正在切换中
               throw new XbbException(ClueErrorCodeEnum.API_ERROR_1111011, ClueErrorCodeEnum.API_ERROR_1111011.getMsg());
            } else {
                companyConfigModel.save(corpid, CompanyConfigEnum.CUSTOMER_PUBLIC_POOL_CHANGE.getAlias(), CompanyConfigEnum.CUSTOMER_PUBLIC_POOL_CHANGE.getName(), CompanyConfigEnum.CUSTOMER_PUBLIC_POOL_CHANGE.getValue());
                //是否切换完成
                paasRedisHelper.setValue(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid, BasicConstant.ONE, TimeConstant.SECONDS_PER_MONTH);
            }

//            Set<String> syncCorpid = paasRedisHelper.getValue4Set(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR, RedisPrefixConstant.SYNCING);
//            if (CollectionsUtil.isEmpty(syncCorpid)) {
//                syncCorpid = new HashSet<>();
//            }
//            if (syncCorpid.contains(corpid)) {
//                //正在切换中
//                throw new XbbException(ErrorCodeEnum.API_ERROR_1111011, ErrorCodeEnum.API_ERROR_1111011.getMsg());
//            } else {
//                syncCorpid.add(corpid);
//                paasRedisHelper.setValue4Set(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR, RedisPrefixConstant.SYNCING, syncCorpid, TimeConstant.SECONDS_PER_MONTH);
//                //是否切换完成
//                paasRedisHelper.setValue(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid, BasicConstant.ONE, TimeConstant.SECONDS_PER_MONTH);
//            }

            //标准模式公海分组转换成高级模式
            syncSeniorPublicGroup(businessType, corpid, userId, customerPublicPoolModel.isSyncPublicGroup());

            //同步退回消息提醒
            syncRemindTime(businessType, corpid, customerPublicPoolModel.isSyncNotice());

            //1同步当前无新建跟进客户退回规则2同步当前无新建机会客户退回规则3同步当前无签订合同客户退回规则
            // 4同步当前最大拥有客户数规则5同步当前前负责人规则6同步当前捞取频率限制规则
            baseVO = syncBackRule(changePublicPoolModel2SeniorDTO);
            publicSeniorLogHelp.savePublicPoolMoDelChangeLog(corpid, businessType, changePublicPoolModel2SeniorDTO.getUserId(), changePublicPoolModel2SeniorDTO.getLoginUserName(),
                    String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_STANDARD_MODEL)),
                    String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_APPLY)),
                    changePublicPoolModel2SeniorDTO.getHttpHeader());

            return baseVO;
        } catch (XbbException e) {
            LOG.error("同步逻辑出错", e);
            //redis 这里手动回滚下
            commonHelp.deleteCustomerPublicPoolModelChangeSenior(corpid);
            paasRedisHelper.removeValue(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid);
            throw e;
        } catch (Exception e) {
            LOG.error("同步逻辑出错", e);
            //redis 这里手动回滚下
            commonHelp.deleteCustomerPublicPoolModelChangeSenior(corpid);
            paasRedisHelper.removeValue(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 同步线索公海池到高级
     *
     * @author lijiangren
     * @date 2022-05-11 10 44
     */
    private ChangePublicPoolModelSeniorVO syncCluePublicPool2Senior(ChangePublicPoolModel2SeniorDTO changePublicPoolModel2SeniorDTO) throws XbbException {
        ChangePublicPoolModelSeniorVO baseVO = new ChangePublicPoolModelSeniorVO();
        Integer businessType = changePublicPoolModel2SeniorDTO.getBusinessType();
        String corpid = changePublicPoolModel2SeniorDTO.getCorpid();
        String userId = changePublicPoolModel2SeniorDTO.getUserId();
        CluePublicPoolModel2SeniorPojo cluePublicPoolModel = changePublicPoolModel2SeniorDTO.getCluePublicPoolModel2SeniorPojo();
        try {
            //是否是旗舰版
            Integer feeType = packageHelp.getFeeType(corpid);
            if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                throw new XbbException(ClueErrorCodeEnum.API_ERROR_1111013, ClueErrorCodeEnum.API_ERROR_1111013.getMsg());
            }
            boolean publicPoolSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
            if (publicPoolSeniorModel) {
                //已经是高级模式，无法切换到高级
                throw new XbbException(ClueErrorCodeEnum.API_ERROR_1111010, ClueErrorCodeEnum.API_ERROR_1111010.getMsg());
            }
            //查公司配置表判断是否数据切换公海模式中
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.CLUE_PUBLIC_POOL_CHANGE.getAlias(), corpid);
            if (Objects.nonNull(companyConfigEntity)) {
                //正在切换中
                throw new XbbException(ClueErrorCodeEnum.API_ERROR_1111011, ClueErrorCodeEnum.API_ERROR_1111011.getMsg());
            } else {
                companyConfigModel.save(corpid, CompanyConfigEnum.CLUE_PUBLIC_POOL_CHANGE.getAlias(), CompanyConfigEnum.CLUE_PUBLIC_POOL_CHANGE.getName(), CompanyConfigEnum.CLUE_PUBLIC_POOL_CHANGE.getValue());
                //是否切换完成
                paasRedisHelper.setValue(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid, BasicConstant.ONE, TimeConstant.SECONDS_PER_MONTH);
            }
//            //查缓存判断是否切换公海模式中
//            Set<String> syncCorpid = paasRedisHelper.getValue4Set(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR, RedisPrefixConstant.SYNCING);
//            if (CollectionsUtil.isEmpty(syncCorpid)) {
//                syncCorpid = new HashSet<>();
//            }
//            if (syncCorpid.contains(corpid)) {
//                //正在切换中
//                throw new XbbException(ErrorCodeEnum.API_ERROR_1111011, ErrorCodeEnum.API_ERROR_1111011.getMsg());
//            } else {
//                syncCorpid.add(corpid);
//                paasRedisHelper.setValue4Set(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR, RedisPrefixConstant.SYNCING, syncCorpid, TimeConstant.SECONDS_PER_MONTH);
//                //是否切换完成
//                paasRedisHelper.setValue(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid, BasicConstant.ONE, TimeConstant.SECONDS_PER_MONTH);
//            }

            //标准模式公海分组转换成高级模式
            syncSeniorPublicGroup(businessType, corpid, userId, cluePublicPoolModel.isSyncPublicGroup());
            //同步退回消息提醒
            syncRemindTime(businessType, corpid, cluePublicPoolModel.isSyncNotice());

            //1同步当前无新建跟进客户退回规则2同步当前无新建机会客户退回规则3同步当前无签订合同客户退回规则
            //4同步当前最大拥有客户数规则5同步当前前负责人规则6同步当前捞取频率限制规则
            baseVO = syncBackRule(changePublicPoolModel2SeniorDTO);
            //5同步自动分配规则
            syncAutoClueAssignment(businessType, corpid, cluePublicPoolModel.isSyncAutoAssign());

            publicSeniorLogHelp.savePublicPoolMoDelChangeLog(corpid, businessType, changePublicPoolModel2SeniorDTO.getUserId(), changePublicPoolModel2SeniorDTO.getLoginUserName(),
                    String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_STANDARD_MODEL)),
                    String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_APPLY)),
                    changePublicPoolModel2SeniorDTO.getHttpHeader());
            return baseVO;
        } catch (XbbException e) {
            LOG.error("同步逻辑出错", e);
            //redis 这里手动回滚下
            commonHelp.deleteCluePublicPoolModelChangeSenior(corpid);
            paasRedisHelper.removeValue(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid);
            throw e;
        } catch (Exception e) {
            LOG.error("同步逻辑出错", e);
            //redis 这里手动回滚下
            commonHelp.deleteCluePublicPoolModelChangeSenior(corpid);
            paasRedisHelper.removeValue(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 同步线索自动分配规则
     *
     * @author lijiangren
     * @date 2022-05-12 16 43
     */
    private void syncAutoClueAssignment(Integer businessType, String corpid, Boolean syncAutoAssign) throws XbbException {

        //公司配置表删除automaticallyAssigned启用标识
        ArrayList<Object> configAlias = new ArrayList<>();
        configAlias.add(CompanyConfigEnum.AUTOMATICALLY_ASSIGNED_SENIOR.getAlias());
        companyConfigModel.updateBatchDelByConfigAlias(DelEnum.DELETE.getDel(), corpid, configAlias);
        //线索特有逻辑高级模式自动分配规则逻辑删除(mode lType=2)
        clueAutoAllocationModel.updateDelByModelType(DelEnum.DELETE.getDel(), corpid, BasicConstant.TWO);

        if (!syncAutoAssign) {
            //不同步标识
            return;
        }

        CompanyConfigEntity configEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.AUTOMATICALLY_ASSIGNED.getAlias(), corpid);
        //自动分配规则未启用（不需要同步）
        if (Objects.isNull(configEntity) || !Objects.equals(configEntity.getConfigValue(), "1")) {
            return;
        }

        //根据业务ID获取所有启用的表单
        List<PaasFormEntityExt> enableFormList = paasFormModel.getFormListDistributor(corpid, businessType, BasicConstant.ZERO);
        if (CollectionsUtil.isEmpty(enableFormList)) {
            return;
        }

        //高级模式下维护自动分配规则
        configEntity.setId(null);
        configEntity.setConfigAlias(CompanyConfigEnum.AUTOMATICALLY_ASSIGNED_SENIOR.getAlias());
        configEntity.setConfigValue(BasicConstant.ONE_STRING);
        companyConfigModel.save(configEntity);

        List<Long> formIdList = enableFormList.stream().map(PaasFormEntityExt::getId).collect(Collectors.toList());
        //获取业务下所有的自动分配
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("formIdIn", formIdList);
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("modelType", BasicConstant.ONE);
        List<ClueAutoAllocationEntity> entitys = clueAutoAllocationModel.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(entitys)) {
            entitys.forEach(item -> {
                //高级模式
                item.setModelType(BasicConstant.TWO);
            });
            clueAutoAllocationModel.insertBatch(entitys);
        }
    }


    /**
     * 调整所属公海分组字段是否开启
     *
     * @author lijiangren
     * @date 2022-05-07 16 43
     */
    private void changePublicGroupFieldEntity4IsOpen(Integer isOpen, Integer businessType, String corpid) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("corpid", corpid);
        param.put("businessType", businessType);
        param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        List<PaasFormExplainEntity> paasFormExplainEntities = paasFormExplainModel.findEntitys(param);
        String attr = CustomerManagementEnum.PUBLIC_GROUP.getAttr();
        if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            attr = ClueEnum.PUBLIC_GROUP.getAttr();
        }
        if (CollectionsUtil.isNotEmpty(paasFormExplainEntities)) {
            for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntities) {
                String explains = paasFormExplainEntity.getExplains();
                List<FieldAttrEntity> fieldAttrList = JSON.parseArray(explains, FieldAttrEntity.class);
                if (CollectionsUtil.isNotEmpty(fieldAttrList)) {
                    String finalAttr = attr;
                    fieldAttrList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), finalAttr)) {
                            item.setIsOpen(isOpen);
                        }
                    });
                    paasFormExplainEntity.setExplains(JSON.toJSONString(fieldAttrList));
                }
            }
        }
        paasFormExplainModel.updateBatch(paasFormExplainEntities, corpid);
    }

    /**
     * 1同步当前无新建跟进客户退回规则
     * 2同步当前无新建机会客户退回规则
     * 3同步当前无签订合同客户退回规则
     * 4同步当前最大拥有客户数规则
     * 5同步当前前负责人规则
     * 6同步当前捞取频率限制规则
     *
     * @author lijiangren
     * @date 2022-04-24 19 50
     * @version
     * @since
     */
    private ChangePublicPoolModelSeniorVO syncBackRule(ChangePublicPoolModel2SeniorDTO changePublicPoolModel2SeniorDTO) throws XbbException {
        ChangePublicPoolModelSeniorVO baseVO = new ChangePublicPoolModelSeniorVO();
        String corpid = changePublicPoolModel2SeniorDTO.getCorpid();
        Integer businessType = changePublicPoolModel2SeniorDTO.getBusinessType();
        String userId = changePublicPoolModel2SeniorDTO.getUserId();
        try {
            //删除高级模式下已经有的退回规则最大客户数等
            transferBackRuleSeniorModel.deleteByBusinessType(corpid, businessType);
            //根据业务ID获取所有启用的表单
            List<PaasFormEntityExt> enableFormList = paasFormModel.getEnableFormListDistributor(corpid, businessType, BasicConstant.ZERO);
            if (CollectionsUtil.isEmpty(enableFormList)) {
                return baseVO;
            }

            List<Long> formIdList = enableFormList.stream().map(PaasFormEntityExt::getId).collect(Collectors.toList());
            //获取业务下所有的标签分组
            Map<String, Object> labelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            labelMap.put("formIdIn", formIdList);
            labelMap.put("corpid", corpid);
            labelMap.put("del", DelEnum.NORMAL.getDel());
            List<LabelEntity> labelList = labelModel.findEntitys(labelMap);
            //标签ID 表单ID
            Map<Long, Long> formIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(labelList)) {
                formIdMap = labelList.stream().collect(Collectors.toMap(LabelEntity::getId, LabelEntity::getFormId));
            }

            //获取退回规则
            Map<String, Object> ruleParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            ruleParam.put("corpid", corpid);
            ruleParam.put("del", DelEnum.NORMAL.getDel());
            ruleParam.put("status", BasicConstant.ONE);

            //不退回标签规则
            Set<Long> labelSet = new HashSet();
            //不退回状态
            Set<String> statusSet = new HashSet();
            //退回标签规则Map，key为表单ID
            Map<Long, List<SyncRuleValuePojo>> labelRuleValuePojoMap = new HashMap<>();
            //退回规则
            List<SyncRuleValuePojo> syncRuleValueList = new ArrayList<>();
            //可以直接同步的到高级的数据 4同步当前最大拥有客户数规则  5同步当前前负责人规则 6同步当前捞取频率限制规则
            List<CustomerRuleEntity> directSyncCustomerRuleList = new ArrayList<>();
            List<ClueRuleEntity> directSyncClueRuleList = new ArrayList<>();

            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                CustomerPublicPoolModel2SeniorPojo customerPublicPoolModel = changePublicPoolModel2SeniorDTO.getCustomerPublicPoolModel2SeniorPojo();
                //客户
                List<CustomerRuleEntity> ruleList = customerRuleModel.findEntitys(ruleParam);
                if (CollectionsUtil.isNotEmpty(ruleList)) {
                    List<CustomerRuleEntity> dealRuleList = new ArrayList<>(ruleList.size());
                    for (CustomerRuleEntity customerRuleEntity : ruleList) {
                        Integer ruleType = customerRuleEntity.getRuleType();
                        //最大客户数、前负责人规则、捞取频率限制规则
                        boolean isOtherSetSync = (Objects.equals(CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE.getCode(), ruleType) && customerPublicPoolModel.isSyncMaxCustomerNum()) ||
                                (Objects.equals(CustomerRuleEnum.PRE_PRINCIPAL_RULE.getCode(), ruleType) && customerPublicPoolModel.isSyncPrePrincipal()) ||
                                (Objects.equals(CustomerRuleEnum.GAIN_RATE_RULE.getCode(), ruleType) && customerPublicPoolModel.isSyncGainRate());

                        boolean isBackRuleSync = (Objects.equals(CustomerRuleEnum.NO_CUSTOMER_COMMUNICATE_RULE.getCode(), ruleType) && customerPublicPoolModel.isSyncNoCustomerCommunicate()) ||
                                (Objects.equals(CustomerRuleEnum.NO_OPPORTUNITY_RULE.getCode(), ruleType) && customerPublicPoolModel.isSyncNoOpportunity()) ||
                                (Objects.equals(CustomerRuleEnum.NO_CONTRACT_RULE.getCode(), ruleType) && customerPublicPoolModel.isSyncNoContact());

                        if (isOtherSetSync) {
                            directSyncCustomerRuleList.add(customerRuleEntity);
                        } else if (isBackRuleSync) {
                            //需要特殊转换的退回规则
                            dealRuleList.add(customerRuleEntity);
                        }
                    }

                    Integer sort = 1;
                    for (CustomerRuleEntity customerRuleEntity : dealRuleList) {
                        //每个循环生成的list规则
                        List<SyncRuleValuePojo> subRuleValueList = new ArrayList<>();
                        String ruleValue = customerRuleEntity.getRuleValue();
                        //1.跟进时间 2.有无机会 3.有无合同
                        Integer ruleType = customerRuleEntity.getRuleType();
                        if (Objects.nonNull(ruleValue)) {
                            JSONObject jsonObject = JSON.parseObject(ruleValue);
                            JSONArray label = jsonObject.getJSONArray("label");
                            JSONArray customerStatus = jsonObject.getJSONArray("customerStatus");
                            if (CollectionsUtil.isNotEmpty(label)) {
                                label.forEach(item -> labelSet.add(Long.valueOf(item.toString())));
                            }
                            if (CollectionsUtil.isNotEmpty(customerStatus)) {
                                customerStatus.forEach(item -> statusSet.add(item.toString()));
                            }
                            //封装转换实体
                            PublicGroupSyncDetailPojo publicGroupSyncDetailPojo = new PublicGroupSyncDetailPojo();
                            publicGroupSyncDetailPojo.setCorpid(corpid);
                            publicGroupSyncDetailPojo.setBusinessType(businessType);
                            publicGroupSyncDetailPojo.setRuleType(ruleType);
                            publicGroupSyncDetailPojo.setRuleValue(ruleValue);
                            publicGroupSyncDetailPojo.setSort(sort);
                            publicGroupSyncDetailPojo.setFormId(formIdList.get(0));
                            publicGroupSyncDetailPojo.setFormIdMap(formIdMap);
                            publicGroupSyncDetailPojo.setLabelRuleValuePojoMap(labelRuleValuePojoMap);
                            publicGroupSyncDetailPojo.setLabelList(labelList);
                            publicGroupSyncDetailPojo = generateDetailRule(publicGroupSyncDetailPojo, subRuleValueList);
                            //处理完毕需要返回的值
                            sort = publicGroupSyncDetailPojo.getSort();
                            labelRuleValuePojoMap = publicGroupSyncDetailPojo.getLabelRuleValuePojoMap();
                        }
                        syncRuleValueList.addAll(subRuleValueList);
                    }

                    //批量插入实体
                    List<TransferBackRuleSeniorEntity> transferBackRuleList = new ArrayList<>();

                    //遍历每个表单 封装不退回和退回规则
                    for (Long formId : formIdList) {
                        TransferBackRuleSeniorEntity transferBackRuleSeniorEntity = new TransferBackRuleSeniorEntity();
                        transferBackRuleSeniorEntity.setCorpid(corpid);
                        transferBackRuleSeniorEntity.setFormId(formId);
                        transferBackRuleSeniorEntity.setStatus(BasicConstant.ONE);
                        transferBackRuleSeniorEntity.setBusinessType(businessType);
                        transferBackRuleSeniorEntity.setCreatorId(userId);
                        //不退回或不转移规则
                        JSONArray jsonData = new JSONArray();
                        //退回或转移规则
                        JSONArray ruleValue = new JSONArray();
                        //不退回的客户状态
                        List<String> statusList = new ArrayList<>(formIdMap.size());
                        //处理标签
                        List<Long> valueList = new ArrayList<>(formIdMap.size());

                        //处理标签
                        if (CollectionsUtil.isNotEmpty(labelSet)) {
                            //不退回匹配规则
                            String symbol = ConditionEnum.INCLUDE.getSymbol();
                            for (Long labelId : labelSet) {
                                if (Objects.equals(formId, formIdMap.get(labelId))) {
                                    valueList.add(labelId);
                                }
                            }

                            if (CollectionsUtil.isNotEmpty(valueList)) {
                                //每个表单的标签不退回规则
                                SyncFilterPojo labelSyncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, CustomerManagementEnum.LABEL.getAttr(), valueList, FieldTypeEnum.COMBO);
                                jsonData.add(labelSyncFilterPojo);
                            }
                        }

                        if (CollectionsUtil.isNotEmpty(statusSet)) {
                            String symbol = ConditionEnum.IN.getSymbol();
                            statusList.addAll(statusSet);
                            SyncFilterPojo customeStatusSyncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, CustomerManagementEnum.TYPE.getAttr(), statusList, FieldTypeEnum.COMBO);
                            jsonData.add(customeStatusSyncFilterPojo);
                        }
                        transferBackRuleSeniorEntity.setJsonData(jsonData);

                        //退回规则
                        //退回规则除标签以外的规则
                        if (CollectionsUtil.isNotEmpty(syncRuleValueList)) {
                            for (SyncRuleValuePojo syncRuleValuePojo : syncRuleValueList) {
                                ruleValue.add(syncRuleValuePojo);
                            }
                        }
                        //标签需要特殊处理
                        List<SyncRuleValuePojo> labelSyncRuleValuePojoList = labelRuleValuePojoMap.get(formId);
                        if (CollectionsUtil.isNotEmpty(labelSyncRuleValuePojoList)) {
                            for (SyncRuleValuePojo syncRuleValuePojo : labelSyncRuleValuePojoList) {
                                ruleValue.add(syncRuleValuePojo);
                            }
                        }

                        if (ruleValue.size() > 10) {
                            //如果规则大于10条需要手动配置.切换不会带到高级版,也不会抛异常.这里做个日志记录
                            LOG.info("该公司{}表单{}模板下退回规则下大于10条，无法同步，请手动配置", corpid, formId);
                            continue;
                            //baseVO.setErrMsg(ErrorCodeEnum.API_ERROR_1111009.getMsg());
                        } else {
                            if (CollectionsUtil.isNotEmpty(ruleValue)) {
                                transferBackRuleSeniorEntity.setRuleValue(ruleValue);
                                //退回规则
                                transferBackRuleSeniorEntity.setType(BasicConstant.TWO);
                                transferBackRuleList.add(transferBackRuleSeniorEntity);
                            }
                        }
                    }

                    //最大客户数、前负责人、捞取频率。特殊处理，不区分表单模板
                    for (CustomerRuleEntity customerRuleEntity : directSyncCustomerRuleList) {
                        TransferBackRuleSeniorEntity transferBackRuleSenior = new TransferBackRuleSeniorEntity();
                        transferBackRuleSenior.setCorpid(corpid);
                        transferBackRuleSenior.setFormId(null);
                        transferBackRuleSenior.setStatus(BasicConstant.ONE);
                        transferBackRuleSenior.setBusinessType(businessType);
                        transferBackRuleSenior.setCreatorId(userId);
                        JSONArray objects = new JSONArray();
                        String ruleValue = customerRuleEntity.getRuleValue();
                        if (customerRuleEntity.getRuleType().equals(CustomerRuleEnum.PRE_PRINCIPAL_RULE.getCode()) || customerRuleEntity.getRuleType().equals(CustomerRuleEnum.GAIN_RATE_RULE.getCode())) {
                            objects = JSON.parseArray(ruleValue);
                        } else {
                            JSONObject jsonObject = JSON.parseObject(ruleValue);
                            objects.add(jsonObject);
                        }
                        transferBackRuleSenior.setRuleValue(objects);
                        transferBackRuleSenior.setJsonData(new JSONArray());
                        if (Objects.equals(CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE.getCode(), customerRuleEntity.getRuleType())) {
                            transferBackRuleSenior.setType(CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode());
                            transferBackRuleList.add(transferBackRuleSenior);
                        }

                        if (Objects.equals(CustomerRuleEnum.PRE_PRINCIPAL_RULE.getCode(), customerRuleEntity.getRuleType())) {
                            transferBackRuleSenior.setType(CustomerSeniorRuleTypeEnum.PRE_PRINCIPAL_RULE.getCode());
                            transferBackRuleList.add(transferBackRuleSenior);
                        }

                        if (Objects.equals(CustomerRuleEnum.GAIN_RATE_RULE.getCode(), customerRuleEntity.getRuleType())) {
                            transferBackRuleSenior.setType(CustomerSeniorRuleTypeEnum.GAIN_RATE_RULE.getCode());
                            transferBackRuleList.add(transferBackRuleSenior);
                        }
                    }

                    if (CollectionsUtil.isNotEmpty(transferBackRuleList)) {
                        transferBackRuleSeniorModel.insertBatch(transferBackRuleList);
                    }
                }

            } else {
                CluePublicPoolModel2SeniorPojo cluePublicPoolModel = changePublicPoolModel2SeniorDTO.getCluePublicPoolModel2SeniorPojo();
                //线索
                List<ClueRuleEntity> ruleList = clueRuleModel.findEntitys(ruleParam);
                if (CollectionsUtil.isNotEmpty(ruleList)) {
                    List<ClueRuleEntity> dealRuleList = new ArrayList<>(ruleList.size());
                    for (ClueRuleEntity clueRuleEntity : ruleList) {
                        Integer ruleType = clueRuleEntity.getRuleType();
                        //最大客户数、前负责人规则、捞取频率限制规则
                        boolean otherSetIsSync = (Objects.equals(ClueRuleEnum.MAX_CLUE_NUM_RULE.getCode(), ruleType) && cluePublicPoolModel.isSyncMaxClueNum()) ||
                                (Objects.equals(ClueRuleEnum.PRE_PRINCIPAL_RULE.getCode(), ruleType) && cluePublicPoolModel.isSyncPrePrincipal()) ||
                                (Objects.equals(ClueRuleEnum.GAIN_RATE_RULE.getCode(), ruleType) && cluePublicPoolModel.isSyncGainRate());
                        if (otherSetIsSync) {
                            directSyncClueRuleList.add(clueRuleEntity);
                        } else if (Objects.equals(ClueRuleEnum.NO_COMMUNICATE_RULE.getCode(), ruleType) && cluePublicPoolModel.isSyncNoCommunicate()) {
                            dealRuleList.add(clueRuleEntity);
                        }
                    }


                    Integer sort = 1;
                    for (ClueRuleEntity clueRuleEntity : dealRuleList) {
                        //每个循环生成的list规则
                        List<SyncRuleValuePojo> subRuleValueList = new ArrayList<>();
                        String ruleValue = clueRuleEntity.getRuleValue();
                        //1.跟进时间 2.有无机会 3.有无合同
                        Integer ruleType = clueRuleEntity.getRuleType();
                        if (Objects.nonNull(ruleValue)) {
                            JSONObject jsonObject = JSON.parseObject(ruleValue);
                            JSONArray label = jsonObject.getJSONArray("label");
                            JSONArray clueStatus = jsonObject.getJSONArray("clueStatus");
                            if (CollectionsUtil.isNotEmpty(label)) {
                                label.forEach(item -> labelSet.add(Long.valueOf(item.toString())));
                            }
                            if (CollectionsUtil.isNotEmpty(clueStatus)) {
                                clueStatus.forEach(item -> statusSet.add(item.toString()));
                            }
                            //封装转换实体
                            PublicGroupSyncDetailPojo publicGroupSyncDetailPojo = new PublicGroupSyncDetailPojo();
                            publicGroupSyncDetailPojo.setCorpid(corpid);
                            publicGroupSyncDetailPojo.setBusinessType(businessType);
                            publicGroupSyncDetailPojo.setFormId(formIdList.get(0));
                            publicGroupSyncDetailPojo.setRuleType(ruleType);
                            publicGroupSyncDetailPojo.setRuleValue(ruleValue);
                            publicGroupSyncDetailPojo.setSort(sort);
                            publicGroupSyncDetailPojo.setFormId(formIdList.get(0));
                            publicGroupSyncDetailPojo.setFormIdMap(formIdMap);
                            publicGroupSyncDetailPojo.setLabelRuleValuePojoMap(labelRuleValuePojoMap);
                            publicGroupSyncDetailPojo.setLabelList(labelList);
                            publicGroupSyncDetailPojo = generateDetailRule(publicGroupSyncDetailPojo, subRuleValueList);
                            //处理完毕需要返回的值
                            sort = publicGroupSyncDetailPojo.getSort();
                            labelRuleValuePojoMap = publicGroupSyncDetailPojo.getLabelRuleValuePojoMap();
                        }
                        syncRuleValueList.addAll(subRuleValueList);
                    }

                    //批量插入实体
                    List<TransferBackRuleSeniorEntity> transferBackRuleList = new ArrayList<>();

                    //遍历每个表单 封装不退回和退回规则
                    for (Long formId : formIdList) {
                        TransferBackRuleSeniorEntity transferBackRuleSeniorEntity = new TransferBackRuleSeniorEntity();
                        transferBackRuleSeniorEntity.setCorpid(corpid);
                        transferBackRuleSeniorEntity.setFormId(formId);
                        transferBackRuleSeniorEntity.setStatus(BasicConstant.ONE);
                        transferBackRuleSeniorEntity.setBusinessType(businessType);
                        transferBackRuleSeniorEntity.setCreatorId(userId);
                        //不退回或不转移规则
                        JSONArray jsonData = new JSONArray();
                        //退回或转移规则
                        JSONArray ruleValue = new JSONArray();

                        //处理标签
                        List<Long> valueList = new ArrayList<>(formIdMap.size());
                        List<String> statusList = new ArrayList<>(formIdMap.size());
                        //处理标签
                        if (CollectionsUtil.isNotEmpty(labelSet)) {
                            //不退回匹配规则
                            String symbol = ConditionEnum.INCLUDE.getSymbol();
                            for (Long labelId : labelSet) {
                                if (Objects.equals(formId, formIdMap.get(labelId))) {
                                    valueList.add(labelId);
                                }
                            }

                            if (CollectionsUtil.isNotEmpty(valueList)) {
                                //每个表单的标签不退回规则
                                SyncFilterPojo labelSyncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, ClueEnum.LABEL.getAttr(), valueList, FieldTypeEnum.COMBO);
                                jsonData.add(labelSyncFilterPojo);
                            }
                        }

                        if (CollectionsUtil.isNotEmpty(statusSet)) {
                            String symbol = ConditionEnum.IN.getSymbol();
                            statusList.addAll(statusSet);
                            SyncFilterPojo customeStatusSyncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, ClueEnum.CLUE_STATUS.getAttr(), statusList, FieldTypeEnum.COMBO);
                            jsonData.add(customeStatusSyncFilterPojo);
                        }
                        transferBackRuleSeniorEntity.setJsonData(jsonData);

                        //退回规则
                        //退回规则除标签以外的规则
                        if (CollectionsUtil.isNotEmpty(syncRuleValueList)) {
                            for (SyncRuleValuePojo syncRuleValuePojo : syncRuleValueList) {
                                ruleValue.add(syncRuleValuePojo);
                            }
                        }
                        //标签需要特殊处理
                        List<SyncRuleValuePojo> labelSyncRuleValuePojoList = labelRuleValuePojoMap.get(formId);
                        if (CollectionsUtil.isNotEmpty(labelSyncRuleValuePojoList)) {
                            for (SyncRuleValuePojo syncRuleValuePojo : labelSyncRuleValuePojoList) {
                                ruleValue.add(syncRuleValuePojo);
                            }
                        }

                        if (ruleValue.size() > 10) {
                            LOG.info("该公司{}表单{}模板下退回规则下大于10条，无法同步，请手动配置", corpid, formId);
                        } else {
                            if (CollectionsUtil.isNotEmpty(ruleValue)) {
                                transferBackRuleSeniorEntity.setRuleValue(ruleValue);
                                //退回规则
                                transferBackRuleSeniorEntity.setType(BasicConstant.TWO);
                                transferBackRuleList.add(transferBackRuleSeniorEntity);
                            }
                        }
                    }

                    //最大客户数、前负责人、捞取频率。特殊处理，不区分表单模板
                    for (ClueRuleEntity clueRuleEntity : directSyncClueRuleList) {
                        TransferBackRuleSeniorEntity transferBackRuleSenior = new TransferBackRuleSeniorEntity();
                        transferBackRuleSenior.setCorpid(corpid);
                        transferBackRuleSenior.setFormId(null);
                        transferBackRuleSenior.setStatus(BasicConstant.ONE);
                        transferBackRuleSenior.setBusinessType(businessType);
                        transferBackRuleSenior.setCreatorId(userId);
                        JSONArray objects = new JSONArray();
                        String ruleValue = clueRuleEntity.getRuleValue();
                        if (clueRuleEntity.getRuleType().equals(ClueRuleEnum.PRE_PRINCIPAL_RULE.getCode()) || clueRuleEntity.getRuleType().equals(ClueRuleEnum.GAIN_RATE_RULE.getCode())) {
                            objects = JSON.parseArray(ruleValue);
                        } else {
                            JSONObject jsonObject = JSON.parseObject(ruleValue);
                            objects.add(jsonObject);
                        }
                        transferBackRuleSenior.setRuleValue(objects);
                        transferBackRuleSenior.setJsonData(new JSONArray());
                        if (Objects.equals(ClueRuleEnum.MAX_CLUE_NUM_RULE.getCode(), clueRuleEntity.getRuleType())) {
                            transferBackRuleSenior.setType(CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode());
                            transferBackRuleList.add(transferBackRuleSenior);
                        }

                        if (Objects.equals(ClueRuleEnum.PRE_PRINCIPAL_RULE.getCode(), clueRuleEntity.getRuleType())) {
                            transferBackRuleSenior.setType(CustomerSeniorRuleTypeEnum.PRE_PRINCIPAL_RULE.getCode());
                            transferBackRuleList.add(transferBackRuleSenior);
                        }

                        if (Objects.equals(ClueRuleEnum.GAIN_RATE_RULE.getCode(), clueRuleEntity.getRuleType())) {
                            transferBackRuleSenior.setType(CustomerSeniorRuleTypeEnum.GAIN_RATE_RULE.getCode());
                            transferBackRuleList.add(transferBackRuleSenior);
                        }
                    }

                    if (CollectionsUtil.isNotEmpty(transferBackRuleList)) {
                        transferBackRuleSeniorModel.insertBatch(transferBackRuleList);
                    }
                }
            }
            return baseVO;
        } catch (Exception e) {
            LOG.error("TransferBackRuleSeniorServiceImpl.syncBackRule同步退回规则失败", corpid);
            throw e;
        }
    }

    /**
     * 处理规则成高级模式下需要的格式
     *
     * @author lijiangren
     * @date 2022-07-05 14 07
     */
    private PublicGroupSyncDetailPojo generateDetailRule(PublicGroupSyncDetailPojo detailPojo, List<SyncRuleValuePojo> subRuleValueList) throws XbbException {
        Integer businessType = detailPojo.getBusinessType();
        Integer ruleType = detailPojo.getRuleType();
        String ruleValue = detailPojo.getRuleValue();
        Long formId = detailPojo.getFormId();
        String corpid = detailPojo.getCorpid();
        Integer sort = detailPojo.getSort();
        List<LabelEntity> labelList = detailPojo.getLabelList();
        //Map<标签ID，表单ID>
        Map<Long, Long> formIdMap = detailPojo.getFormIdMap();
        Map<Long, List<SyncRuleValuePojo>> labelRuleValuePojoMap = detailPojo.getLabelRuleValuePojoMap();

        //条件 equal
        String symbol = ConditionEnum.EQUAL.getSymbol();
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            //ruleType 1.跟进时间 2.有无机会 3.有无合同
            JSONObject jsonObject = JSON.parseObject(ruleValue);
            //退回规则
            JSONArray restrict = jsonObject.getJSONArray("restrict");
            //0:全部客户  1:客户状态  2:星级  3:标签
            Integer type = jsonObject.getInteger("type");

            String ruleNameDesc = I18nMessageUtil.getMessage(CustomerRuleConstant.NO_CUSTOMER_COMMUNICATE_BACK_PUBLIC);
            if (Objects.equals(CustomerRuleEnum.NO_CONTRACT_RULE.getCode(), ruleType)) {
                ruleNameDesc = I18nMessageUtil.getMessage(CustomerRuleConstant.NO_SIGN_CONTRACT_BACK_PUBLIC);
            } else if (Objects.equals(CustomerRuleEnum.NO_OPPORTUNITY_RULE.getCode(), ruleType)) {
                ruleNameDesc = I18nMessageUtil.getMessage(CustomerRuleConstant.NO_OPPORTUNITY_BACK_PUBLIC);
            }
            //全部客户统一设置
            if (Objects.equals(type, CustomerChildTypeEnum.CUSTOMER_CHILD_ZERO_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //规则rule
                        List filterList = stringListMap.get(key);
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, ruleNameDesc, Boolean.TRUE, businessType, new SyncFilterPojo(), filterList);
                        subRuleValueList.add(syncRuleValuePojo);
                        sort = sort + 1;
                    }
                }
            }

            //根据客户状态设置
            if (Objects.equals(type, CustomerChildTypeEnum.CUSTOMER_CHILD_ONE_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //规则rule
                        List filterList = stringListMap.get(key);
                        //条件值
                        ArrayList<String> valueList = new ArrayList<>();
                        valueList.add(key);
                        SyncFilterPojo syncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, CustomerManagementEnum.TYPE.getAttr(), valueList, FieldTypeEnum.COMBO);
                        String namePre = "";
                        if (Objects.nonNull(syncFilterPojo.getItems())) {
                            JSONArray items = JSON.parseArray(syncFilterPojo.getItems().toString());
                            for (Object item : items) {
                                JSONObject jsonItem = JSON.parseObject(item.toString());
                                if (Objects.equals(key, jsonItem.get("value"))) {
                                    namePre = jsonItem.getString("text");
                                }
                            }
                        }
                        String name = namePre.concat(ruleNameDesc);
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, name, Boolean.FALSE, businessType, syncFilterPojo, filterList);
                        subRuleValueList.add(syncRuleValuePojo);
                        sort = sort + 1;
                    }
                }
            }

            //星级
            if (Objects.equals(type, CustomerChildTypeEnum.CUSTOMER_CHILD_TWO_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //规则rule
                        List filterList = stringListMap.get(key);
                        //条件值
                        ArrayList<Integer> valueList = new ArrayList<>();
                        valueList.add(Integer.valueOf(key));
                        SyncFilterPojo syncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, CustomerManagementEnum.IMPORTANT_DEGREE.getAttr(), valueList, FieldTypeEnum.STAR);
                        //星级特殊处理。
                        List<ItemDataPoJo> itemDataPoJos = listOfStar();
                        syncFilterPojo.setItems(itemDataPoJos);
                        String namePre = "";
                        for (ItemDataPoJo itemDataPoJo : itemDataPoJos) {
                            if (Objects.equals(key, itemDataPoJo.getValue().toString())) {
                                namePre = itemDataPoJo.getText().toString();
                            }
                        }
                        String name = namePre.concat(ruleNameDesc);
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, name, Boolean.FALSE, businessType, syncFilterPojo, filterList);
                        subRuleValueList.add(syncRuleValuePojo);
                        sort = sort + 1;
                    }
                }
            }

            //标签
            if (Objects.equals(type, CustomerChildTypeEnum.CUSTOMER_CHILD_THREE_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    //标签ID
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //规则rule
                        List filterList = stringListMap.get(key);
                        //条件值
                        ArrayList<Long> valueList = new ArrayList<>();
                        valueList.add(Long.valueOf(key));
                        SyncFilterPojo syncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, CustomerManagementEnum.LABEL.getAttr(), valueList, FieldTypeEnum.LABEL);
                        LabelEntity labelEntity = labelList.stream().filter(t -> Objects.equals(key, t.getId().toString())).findAny().orElse(null);
                        String namePre = "";
                        if (Objects.nonNull(labelEntity)) {
                            namePre = labelEntity.getName();
                        }
                        String name = namePre.concat(ruleNameDesc);
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, name, Boolean.FALSE, businessType, syncFilterPojo, filterList);
                        //Map<标签ID，表单ID>
                        Long labelFormId = formIdMap.get(Long.valueOf(key));
                        if (labelRuleValuePojoMap.containsKey(labelFormId)) {
                            List<SyncRuleValuePojo> syncRuleValuePojoList = labelRuleValuePojoMap.get(labelFormId);
                            syncRuleValuePojoList.add(syncRuleValuePojo);
                        } else {
                            List<SyncRuleValuePojo> syncRuleValuePojoList = new ArrayList();
                            syncRuleValuePojoList.add(syncRuleValuePojo);
                            labelRuleValuePojoMap.put(labelFormId, syncRuleValuePojoList);
                        }
                        sort = sort + 1;
                    }
                }
            }
        } else {
            //ruleType 1.跟进时间
            JSONObject jsonObject = JSON.parseObject(ruleValue);
            //规则
            JSONArray restrict = jsonObject.getJSONArray("restrict");
            //0:全部线索  1:线索状态  2:标签
            Integer type = jsonObject.getInteger("type");
            //全部线索统一设置
            if (Objects.equals(type, ClueChildTypeEnum.CLUE_CHILD_ZERO_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //规则rule
                        List filterList = stringListMap.get(key);
                        String name = I18nMessageUtil.getMessage(CustomerRuleConstant.NO_CLUE_COMMUNICATE_BACK_PUBLIC);
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, name, Boolean.TRUE, businessType, new SyncFilterPojo(), filterList);
                        subRuleValueList.add(syncRuleValuePojo);
                        sort = sort + 1;
                    }
                }
            }

            //根据线索状态设置
            if (Objects.equals(type, ClueChildTypeEnum.CLUE_CHILD_ONE_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //规则rule
                        List filterList = stringListMap.get(key);
                        //条件值
                        ArrayList<String> valueList = new ArrayList<>();
                        valueList.add(key);
                        SyncFilterPojo syncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, ClueEnum.CLUE_STATUS.getAttr(), valueList, FieldTypeEnum.COMBO);
                        String namePre = "";
                        if (Objects.nonNull(syncFilterPojo.getItems())) {
                            JSONArray items = JSON.parseArray(syncFilterPojo.getItems().toString());
                            for (Object item : items) {
                                JSONObject jsonItem = JSON.parseObject(item.toString());
                                if (Objects.equals(key, jsonItem.get("value"))) {
                                    namePre = jsonItem.getString("text");
                                }
                            }
                        }

                        String name = namePre.concat(I18nMessageUtil.getMessage(CustomerRuleConstant.NO_CLUE_COMMUNICATE_BACK_PUBLIC));
                        //封装SyncRuleValuePojo实体
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, name, Boolean.FALSE, businessType, syncFilterPojo, filterList);
                        subRuleValueList.add(syncRuleValuePojo);
                        sort = sort + 1;
                    }
                }
            }

            //线索标签
            if (Objects.equals(type, ClueChildTypeEnum.CLUE_CHILD_TWO_STAR.getCode())) {
                if (CollectionsUtil.isNotEmpty(restrict)) {
                    //标签ID
                    Map<String, List> stringListMap = convertRestrict(businessType, ruleType, type, restrict);
                    for (String key : stringListMap.keySet()) {
                        //过滤规则
                        List filterList = stringListMap.get(key);
                        //条件值
                        ArrayList<Long> valueList = new ArrayList<>();
                        valueList.add(Long.valueOf(key));
                        SyncFilterPojo syncFilterPojo = generateSyncFilterPojo(formId, corpid, symbol, ClueEnum.LABEL.getAttr(), valueList, FieldTypeEnum.LABEL);
                        LabelEntity labelEntity = labelList.stream().filter(t -> Objects.equals(key, t.getId().toString())).findAny().orElse(null);
                        String namePre = "";
                        if (Objects.nonNull(labelEntity)) {
                            namePre = labelEntity.getName();
                        }
                        String name = namePre.concat(I18nMessageUtil.getMessage(CustomerRuleConstant.NO_CLUE_COMMUNICATE_BACK_PUBLIC));
                        //封装SyncRuleValuePojo实体
                        SyncRuleValuePojo syncRuleValuePojo = generateSyncRuleValuePojo(sort, name, Boolean.FALSE, businessType, syncFilterPojo, filterList);
                        //Map<标签ID，表单ID>
                        Long labelFormId = formIdMap.get(Long.valueOf(key));
                        if (labelRuleValuePojoMap.containsKey(labelFormId)) {
                            List<SyncRuleValuePojo> syncRuleValuePojoList = labelRuleValuePojoMap.get(labelFormId);
                            syncRuleValuePojoList.add(syncRuleValuePojo);
                        } else {
                            List<SyncRuleValuePojo> syncRuleValuePojoList = new ArrayList();
                            syncRuleValuePojoList.add(syncRuleValuePojo);
                            labelRuleValuePojoMap.put(labelFormId, syncRuleValuePojoList);
                        }
                        sort = sort + 1;
                    }
                }
            }

        }
        detailPojo.setSort(sort);
        detailPojo.setLabelRuleValuePojoMap(labelRuleValuePojoMap);
        return detailPojo;
    }

    /**
     * 处理规则成高级模式下需要的格式
     * isAllSet 是否是全部客户(线索)统一设置
     *
     * @author lijiangren
     * @date 2022-07-05 14 07
     */
    private SyncRuleValuePojo generateSyncRuleValuePojo(Integer sort, String name, Boolean isAllSet, Integer businessType, SyncFilterPojo syncFilterPojo, List filterList) {
        SeniorFixedGroupEnum seniorFixedGroupEnum = SeniorFixedGroupEnum.ALL_CUSTOMER_GROUP;
        if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            seniorFixedGroupEnum = SeniorFixedGroupEnum.ALL_CLUE_GROUP;
        }
        //规则rule
        SyncRuleValuePojo syncRuleValuePojo = new SyncRuleValuePojo();
        SyncTriggerScreenPojo syncTriggerScreenPojo = new SyncTriggerScreenPojo(filterList, BasicConstant.ONE);
        syncRuleValuePojo.setTriggerScreen(syncTriggerScreenPojo);
        //只有单个条件
        List<SyncFilterPojo> filterRule = new ArrayList<>();
        SyncFilterScreenPojo syncFilterScreenPojo = new SyncFilterScreenPojo();
        syncFilterScreenPojo.setFilterRule(filterRule);
        if (isAllSet) {
            syncFilterScreenPojo.setFilterType(BasicConstant.ONE);
        } else {
            //全部统一设置场景filterScreen无需空数组包含空对象
            filterRule.add(syncFilterPojo);
            syncFilterScreenPojo.setFilterType(BasicConstant.TWO);
        }
        syncRuleValuePojo.setFilterScreen(syncFilterScreenPojo);
        syncRuleValuePojo.setName(name);
        syncRuleValuePojo.setSort(sort);
        syncRuleValuePojo.setObjectiveGroup(new SyncLabelValuePojo(SeniorFixedGroupEnum.CURRENT_GROUP.getLabel(), SeniorFixedGroupEnum.CURRENT_GROUP.getId()));
        //适用范围
        List<SyncLabelValuePojo> applyScope = new ArrayList<>();
        SyncLabelValuePojo syncLabelValuePojo = new SyncLabelValuePojo(seniorFixedGroupEnum.getLabel(), seniorFixedGroupEnum.getId());
        applyScope.add(syncLabelValuePojo);
        syncRuleValuePojo.setApplyScope(applyScope);
        return syncRuleValuePojo;
    }

    private List<ItemDataPoJo> listOfStar() {
        List<ItemDataPoJo> list = new ArrayList<>();
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.LESS_THAN_ONE_STAR), 1));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.TWO_STAR), 2));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.THREE_STAR), 3));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.FOUR_STAR), 4));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.FIVE_STAR), 5));
        return DataUtil.filterRepetition(list);
    }

    private SyncFilterPojo generateSyncFilterPojo(Long formId, String corpid, String symbol, String attr, List valueList, FieldTypeEnum combo) throws XbbException {
        SyncFilterPojo syncFilterPojo = new SyncFilterPojo();
        List<ConditionClass> conditions = ConditionListHelp.getConditionList(combo, BasicConstant.ONE);
        syncFilterPojo.setWhereList(conditions);
        SyncConditionPojo syncConditionPojo = publicGroupService.getConditionByAttr(attr, formId, corpid);
        List<JSONObject> selectInfo = syncConditionPojo.getSelectInfo();
        FieldAttrEntity fieldAttrEntity = syncConditionPojo.getFieldAttrEntity();
        Map<String, Object> field = new HashMap<>();
        JSONArray items = new JSONArray();
        if (Objects.nonNull(fieldAttrEntity)) {
            if (CollectionsUtil.isNotEmpty(selectInfo)) {
                JSONObject conditionAttr = selectInfo.get(0);
                JSONArray symbolArray = conditionAttr.getJSONArray("symbolArray");
                JSONArray valueArrMap = conditionAttr.getJSONArray("valueArrMap");
                Object symbolArrayObject = CloneUtil.deepClone(symbolArray);
                Object valueArrMapObject = CloneUtil.deepClone(valueArrMap);
                syncFilterPojo.setSymbolArray(symbolArrayObject);
                syncFilterPojo.setValueArrMap(valueArrMapObject);
                field.put("name", fieldAttrEntity.getAttrName());
                field.put("type", fieldAttrEntity.getFieldType());
                field.put("alias", fieldAttrEntity.getAttr());
                field.put("symbol", "equal");
                field.put("isRedundant", fieldAttrEntity.getIsRedundant());
                field.put("symbolArray", symbolArray);
                field.put("valueArrMap", valueArrMap);
                for (Object item : valueArrMap) {
                    JSONObject jsonObject = JSON.parseObject(item.toString());
                    jsonObject.put("isOther", BasicConstant.ZERO);
                    jsonObject.put("text", jsonObject.getString("key"));
                    jsonObject.remove("key");
                    items.add(jsonObject);
                }
            }
            Object valueItems = CloneUtil.deepClone(items);
            syncFilterPojo.setValueItems(valueItems);
            syncFilterPojo.setField(field);
            syncFilterPojo.setItems(items);
            syncFilterPojo.setSymbol(symbol);
            syncFilterPojo.setAttr(fieldAttrEntity.getAttr());
            syncFilterPojo.setFieldType(fieldAttrEntity.getFieldType());
            syncFilterPojo.setName(fieldAttrEntity.getAttrName());
            syncFilterPojo.setFieldType(fieldAttrEntity.getFieldType());
            syncFilterPojo.setFormId(fieldAttrEntity.getFormId());
            syncFilterPojo.setValue(valueList);
        }
        return syncFilterPojo;
    }

    private Map<String, List> convertRestrict(Integer businessType, Integer ruleType, Integer type, JSONArray restrict) throws XbbException {

        Map<String, List> statusMap = new HashMap(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (Object object : restrict) {
            JSONObject itemJson = JSON.parseObject(object.toString());
            JSONArray array = itemJson.getJSONArray("array");
            JSONArray depts = itemJson.getJSONArray("depts");
            JSONArray users = itemJson.getJSONArray("users");
            JSONArray roles = itemJson.getJSONArray("roles");
            for (Object obj : array) {
                JSONObject itemJsonObj = JSON.parseObject(obj.toString());
                JSONArray keyList = new JSONArray();
                //线索和客户的标签类型不一致，由于标签规则的key是数组，其他规则都是单个对象
                boolean isLabel = (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(type, BasicConstant.THREE)) ||
                        (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(type, BasicConstant.TWO));
                if (isLabel) {
                    keyList = itemJsonObj.getJSONArray("key");
                } else {
                    keyList.add(itemJsonObj.getString("key"));
                }
                for (Object singleKey : keyList) {
                    Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    String keyStr = singleKey.toString();
                    String value = itemJsonObj.getString("value");
                    if (Objects.isNull(value)) {
                        continue;
                    }
                    map.put("value", value);
                    map.put("chooseType", ruleType);

                    if (CollectionsUtil.isNotEmpty(depts)) {
                        map.put("depts", depts);
                    }
                    if (CollectionsUtil.isNotEmpty(users)) {
                        map.put("users", users);
                    }
                    if (CollectionsUtil.isNotEmpty(roles)) {
                        map.put("roles", roles);
                    }
                    if (statusMap.containsKey(keyStr)) {
                        List list = statusMap.get(keyStr);
                        list.add(map);
                    } else {
                        List list = new ArrayList();
                        list.add(map);
                        statusMap.put(keyStr, list);
                    }
                }
            }
        }
        return statusMap;
    }

    private void syncRemindTime(Integer businessType, String corpid, Boolean syncNotice) throws XbbException {
        try {
            List seniorConfigAliasList = new ArrayList<>();
            String configAlias = CompanyConfigEnum.PUBLIC_RULE_REMIND_TIME.getAlias();
            String newConfigAlias = CompanyConfigEnum.PUBLIC_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias();
            //高级模式客户消息提醒配置
            seniorConfigAliasList.add(CompanyConfigEnum.PUBLIC_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias());
            seniorConfigAliasList.add(CompanyConfigEnum.TRANSFER_RULE_CUSTOMER_SENIOR_REMIND_TIME.getAlias());

            if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                configAlias = CompanyConfigEnum.CLUE_PUBLIC_RULE_REMIND_TIME.getAlias();
                newConfigAlias = CompanyConfigEnum.PUBLIC_RULE_CLUE_SENIOR_REMIND_TIME.getAlias();
                //高级模式线索消息提醒配置
                seniorConfigAliasList.add(CompanyConfigEnum.PUBLIC_RULE_CLUE_SENIOR_REMIND_TIME.getAlias());
                seniorConfigAliasList.add(CompanyConfigEnum.TRANSFER_RULE_CLUE_SENIOR_REMIND_TIME.getAlias());
            }
            //删除高级模式下提醒数据
            companyConfigModel.updateBatchDelByConfigAlias(DelEnum.DELETE.getDel(), corpid, seniorConfigAliasList);
            if (!syncNotice) {
                //不同步
                return;
            }

            CompanyConfigEntity companyConfig = companyConfigModel.initConfigEntity(corpid, configAlias);
            if (companyConfig != null) {
                //数据存在才需要更新，数据不存在则用默认的
                companyConfig.setId(null);
                companyConfig.setConfigAlias(newConfigAlias);
                companyConfigModel.insert(companyConfig);
            }
        } catch (Exception e) {
            LOG.error("TransferBackRuleSeniorServiceImpl.syncRemindTime同步消息提醒时间失败", corpid);
            throw e;
        }

    }


    /**
     * 标准模式公海分组转换成高级模式
     *
     * @author lijiangren
     * @date 2022-04-24 16 44
     */
    private void syncSeniorPublicGroup(Integer businessType, String corpid, String userId, Boolean syncPublicGroup) throws XbbException {
        try {
            //先删除高级模式下已经有的分组
            publicGroupSeniorModel.deleteByBusinessType(corpid, businessType);
            if (!syncPublicGroup) {
                //不同步
                return;
            }
            //根据业务ID获取所有启用的表单
            List<PaasFormEntityExt> enableFormList = paasFormModel.getFormListDistributor(corpid, businessType, BasicConstant.ZERO);
            if (CollectionsUtil.isEmpty(enableFormList)) {
                return;
            }
            List<Long> formIdList = enableFormList.stream().map(PaasFormEntityExt::getId).collect(Collectors.toList());
            //获取标准模式下公海池分组
            List<PublicGroupEntity> publicGroupList = publicGroupService.getListFormIdList(formIdList, corpid);
            if (CollectionsUtil.isNotEmpty(publicGroupList)) {
                Map<Long, List<PublicGroupEntity>> collect = publicGroupList.stream().collect(Collectors.groupingBy(PublicGroupEntity::getFormId));
                List<PublicGroupSeniorEntity> seniorPublicList = new ArrayList<>();
                for (Long formId : formIdList) {
                    List<PublicGroupEntity> publicGroupEntities = collect.get(formId);
                    if (CollectionsUtil.isNotEmpty(publicGroupEntities)) {
                        //初始化无分组
                        PublicGroupSeniorEntity noGroupSeniorEntity = publicGroupSeniorModel.initNoPublicGroup(corpid, businessType, userId, formId);
                        seniorPublicList.add(noGroupSeniorEntity);
                        Integer sort = 1;
                        for (PublicGroupEntity publicGroupEntity : publicGroupEntities) {
                            PublicGroupSeniorEntity publicGroupSeniorEntity = new PublicGroupSeniorEntity();
                            publicGroupSeniorEntity.setCorpid(publicGroupEntity.getCorpid());
                            publicGroupSeniorEntity.setName(publicGroupEntity.getName());
                            publicGroupSeniorEntity.setBusinessType(businessType);
                            publicGroupSeniorEntity.setLevel(BasicConstant.ONE);
                            publicGroupSeniorEntity.setParentId(BasicConstant.ZERO_LONG);
                            publicGroupSeniorEntity.setFormId(publicGroupEntity.getFormId());
                            publicGroupSeniorEntity.setJsonData(publicGroupEntity.getJsonData());
                            publicGroupSeniorEntity.setCreatorId(publicGroupEntity.getCreatorId());
                            publicGroupSeniorEntity.setScopeRule(publicGroupEntity.getScopeRule());
                            publicGroupSeniorEntity.setModifierId(publicGroupEntity.getModifierId());
                            publicGroupSeniorEntity.setStatus(publicGroupEntity.getEnable());
                            publicGroupSeniorEntity.setSort(sort);
                            publicGroupSeniorEntity.setGroupType(SeniorPublicGroupTypeEnum.OTHER_PUBLIC_GROUP.getType());
                            publicGroupSeniorEntity.setAdminScopeRule(new JSONArray());
                            seniorPublicList.add(publicGroupSeniorEntity);
                            sort++;
                        }
                    }
                }

                if (CollectionsUtil.isNotEmpty(seniorPublicList)) {
                    publicGroupSeniorModel.insertBatch(seniorPublicList);
                }
            }
        } catch (Exception e) {
            LOG.error("TransferBackRuleSeniorServiceImpl.syncSeniorPublicGroup同步分组失败", corpid);
            throw e;
        }
    }


    /**
     * 初始化表单解释时，特殊处理表单解释，确保公海分组字段解释在高级模式下保持开启
     * 涉及到的表单模板：客户、线索
     *
     * @param xbbRefTypeEnum
     * @param fieldAttrEntity
     * @author lijiangren
     * @version v1.0
     * @since v1.0
     */
    @Override
    public void handlePublicGroupFieldEntity4Init(String corpid, XbbRefTypeEnum xbbRefTypeEnum, FieldAttrEntity fieldAttrEntity) throws XbbException {
        if (Objects.isNull(corpid) || Objects.isNull(xbbRefTypeEnum) || Objects.isNull(fieldAttrEntity)) {
            return;
        }

        Integer businessType = xbbRefTypeEnum.getCode();

        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.PUBLIC_GROUP.getAttr())) {
                if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)) {
                    fieldAttrEntity.setIsOpen(BasicConstant.ONE);
                }
            }

        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.PUBLIC_GROUP.getAttr())) {
                if (commonHelp.isCluePublicPoolSeniorModel(corpid)) {
                    fieldAttrEntity.setIsOpen(BasicConstant.ONE);
                }
            }
        }

    }

    /**
     * 切换到标准模式
     *
     * @param changePublicPoolModel2StandardDTO
     * @author lijiangren
     * @version v1.0
     * @since v1.0
     */
    @Override
    public BaseVO changePublicPoolModel2Standard(ChangePublicPoolModel2StandardDTO changePublicPoolModel2StandardDTO) throws XbbException {
        BaseVO baseVO = new BaseVO();
        String corpid = changePublicPoolModel2StandardDTO.getCorpid();
        Integer businessType = changePublicPoolModel2StandardDTO.getBusinessType();
        try {
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                boolean publicPoolSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
                if (!publicPoolSeniorModel) {
                    //已经是标准模式，无法切换到标准
                    return baseVO;
                }
                //公司配置表关闭线索公海池高级模式
                commonHelp.closeCustomerPublicPoolSeniorModel(corpid);
                tagLinkModel.deleteReturnPublicTags(corpid, TagTypeEnum.TRANSFER_CUSTOMER_RULE.getCode());
            } else {
                boolean publicPoolSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
                if (!publicPoolSeniorModel) {
                    //已经是标准模式，无法切换到标准
                    return baseVO;
                }
                //公司配置表关闭线索公海池高级模式
                commonHelp.closeCluePublicPoolSeniorModel(corpid);
                tagLinkModel.deleteReturnPublicTags(corpid, TagTypeEnum.TRANSFER_CLUE_RULE.getCode());
            }

            //所属公海分组字段放入未启用状态
            changePublicGroupFieldEntity4IsOpen(BasicConstant.ZERO, businessType, corpid);

            publicSeniorLogHelp.savePublicPoolMoDelChangeLog(corpid, businessType, changePublicPoolModel2StandardDTO.getUserId(), changePublicPoolModel2StandardDTO.getLoginUserName(),
                    String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_STANDARD_MODEL)),
                    String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_CONFIRM)),
                    changePublicPoolModel2StandardDTO.getHttpHeader());

        } catch (Exception e) {
            LOG.error("同步到标准模式逻辑出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return baseVO;
    }

    /**
     * 获取公海切换状态
     *
     * @param changePublicPoolModelStatusDTO
     * @author lijiangren
     * @version v1.0
     * @since v1.0
     */
    @Override
    public ChangePublicPoolModelStatusVO getChangePublicPoolStatus(ChangePublicPoolModelStatusDTO changePublicPoolModelStatusDTO) throws XbbException {
        try {
            ChangePublicPoolModelStatusVO vo = new ChangePublicPoolModelStatusVO();
            String corpid = changePublicPoolModelStatusDTO.getCorpid();
            Integer businessType = changePublicPoolModelStatusDTO.getBusinessType();
            String changeSenior = CompanyConfigEnum.CUSTOMER_PUBLIC_POOL_CHANGE.getAlias();
            String changeSeniorComplete = RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE;
            if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                changeSenior = CompanyConfigEnum.CLUE_PUBLIC_POOL_CHANGE.getAlias();
                changeSeniorComplete = RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE;
            }
            Integer status = BasicConstant.ZERO;
            //查缓存判断是否数据切换公海模式中
            //1:配置正在切换中
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(changeSenior, corpid);
            //2:数据切换完成
            String value = paasRedisHelper.getValue(changeSeniorComplete, corpid);
            //客户触发过切换，脚本也执行过已经到确认切换状态，超过一个月未确认，缓存失效。需要会到标准模式
            if (Objects.nonNull(companyConfigEntity) && Objects.isNull(value)) {
                vo.setStatus(status);
                //删除changeSenior标识
                companyConfigModel.deleteByKey(companyConfigEntity.getId(),corpid);
                return vo;
            }
            if (Objects.nonNull(companyConfigEntity) && Objects.equals(companyConfigEntity.getConfigValue(),BasicConstant.ONE_STRING)) {
                status = BasicConstant.ONE;
            }

            if (Objects.nonNull(value) && Objects.equals(value, BasicConstant.TWO.toString())) {
                status = BasicConstant.TWO;
            }
            //3:用户手动点击确认切换,近一个月已经切换过高级模式了
            if (Objects.nonNull(value) && Objects.equals(value, BasicConstant.THREE.toString())) {
                status = BasicConstant.THREE;
            }

            vo.setStatus(status);
            return vo;
        } catch (Exception e) {
            LOG.error("获取公海池切换状态错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 确认切换公海池完成
     *
     * @param confirmChangePublicPoolModelDTO
     * @author lijiangren
     * @version v1.0
     * @since v1.0
     */
    @Override
    public BaseVO confirmChangePublicPoolComplete(ConfirmChangePublicPoolModelDTO confirmChangePublicPoolModelDTO) throws XbbException {
        BaseVO baseVO = new BaseVO();
        String corpid = confirmChangePublicPoolModelDTO.getCorpid();
        Integer businessType = confirmChangePublicPoolModelDTO.getBusinessType();
        String userId = confirmChangePublicPoolModelDTO.getUserId();
        String loginUserName = confirmChangePublicPoolModelDTO.getLoginUserName();
        try {

            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                //公司配置表开启客户公海池高级模式
                commonHelp.openCustomerPublicPoolSeniorModel(corpid);
                //redis移除已经正在同步的标识
                commonHelp.deleteCustomerPublicPoolModelChangeSenior(corpid);
                //redis移除是否同步完成的标识(有效期30天)
                paasRedisHelper.setValue(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid, BasicConstant.THREE, TimeConstant.SECONDS_PER_MONTH);
                //paasRedisHelper.removeValue(RedisPrefixConstant.CUSTOMER_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid);

            } else {
                //线索
                //公司配置表开启客户公海池高级模式
                commonHelp.openCluePublicPoolSeniorModel(corpid);
                //redis移除已经正在同步的标识
                commonHelp.deleteCluePublicPoolModelChangeSenior(corpid);
                //redis移除是否同步完成的标识(有效期30天)
                //paasRedisHelper.removeValue(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid);
                paasRedisHelper.setValue(RedisPrefixConstant.CLUE_PUBLIC_POOL_MODEL_CHANGE_SENIOR_COMPLETE, corpid, BasicConstant.THREE, TimeConstant.SECONDS_PER_MONTH);

            }
            //改变解析，所属公海分组字段启用状态
            changePublicGroupFieldEntity4IsOpen(BasicConstant.ONE, businessType, corpid);
            publicSeniorLogHelp.savePublicPoolMoDelChangeLog(corpid, businessType, userId, loginUserName, String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_SENIOR_MODEL)), String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LOG_MEMO_CONFIRM)), confirmChangePublicPoolModelDTO.getHttpHeader());
            return baseVO;
        } catch (Exception e) {
            LOG.error("确认切换公海池完成错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 非旗舰版切换公海池咨询客户生成一条销售机会
     */
    @Override
    public BaseVO askPublicPoolSeniorModel(BaseDTO baseDTO) {
        BaseVO baseVO = new BaseVO();
        try {
//            //推送一条销售机会
            CompanyEntity byKey = companyModel.getByKey(baseDTO.getCorpid());
            AppModuleSaveDTO saveDTO = new AppModuleSaveDTO();
            BeanUtil.copyProperties(baseDTO, saveDTO);
            saveDTO.setCompanyName(byKey.getCorpName());
            saveDTO.setAlias(ValueAddedTypeEnum.PUBLIC_POOL_SENIOR_ASK.getAlias());
            appModuleService.addSalesOpportunity(saveDTO);
        } catch (Exception e) {
            LOG.error("公海池升级高咨询客户生成销售机会失败！");
        }
        return baseVO;
    }

}
